Merge branch 'master' into extended-easysetup
authoruzchoi <uzchoi@samsung.com>
Mon, 11 Jul 2016 02:54:47 +0000 (11:54 +0900)
committeruzchoi <uzchoi@samsung.com>
Mon, 11 Jul 2016 02:56:51 +0000 (11:56 +0900)
Change-Id: Ifad200718955d1f1382178e72c36866b538af622

526 files changed:
.gbs.conf [new file with mode: 0644]
.gitignore
SConstruct
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/JniEntityHandler.cpp
android/android_api/base/jni/JniListenerManager.h
android/android_api/base/jni/JniOcDirectPairDevice.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOcDirectPairDevice.h [new file with mode: 0644]
android/android_api/base/jni/JniOcPlatform.cpp
android/android_api/base/jni/JniOcPlatform.h
android/android_api/base/jni/JniOcPresenceHandle.cpp
android/android_api/base/jni/JniOcRepresentation.cpp
android/android_api/base/jni/JniOcRepresentation.h
android/android_api/base/jni/JniOcRequestHandle.cpp
android/android_api/base/jni/JniOcResource.cpp
android/android_api/base/jni/JniOcResourceHandle.cpp
android/android_api/base/jni/JniOcResourceIdentifier.cpp
android/android_api/base/jni/JniOcResourceRequest.cpp
android/android_api/base/jni/JniOcResourceResponse.cpp
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/JniOnDPDevicesFoundListener.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOnDPDevicesFoundListener.h [new file with mode: 0644]
android/android_api/base/jni/JniOnDeleteListener.cpp
android/android_api/base/jni/JniOnDeviceInfoListener.cpp
android/android_api/base/jni/JniOnDirectPairingListener.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOnDirectPairingListener.h [new file with mode: 0644]
android/android_api/base/jni/JniOnGetListener.cpp
android/android_api/base/jni/JniOnObserveListener.cpp
android/android_api/base/jni/JniOnPlatformInfoListener.cpp
android/android_api/base/jni/JniOnPostListener.cpp
android/android_api/base/jni/JniOnPresenceListener.cpp
android/android_api/base/jni/JniOnPutListener.cpp
android/android_api/base/jni/JniOnResourceFoundListener.cpp
android/android_api/base/jni/JniPinCheckListener.cpp
android/android_api/base/jni/JniProvisionResultListner.cpp
android/android_api/base/jni/JniProvisionResultListner.h
android/android_api/base/jni/JniSecureUtils.cpp
android/android_api/base/jni/JniSecureUtils.h
android/android_api/base/jni/JniUtils.cpp
android/android_api/base/jni/JniUtils.h
android/android_api/base/src/androidTest/java/org/iotivity/base/SmokeTest.java
android/android_api/base/src/main/java/org/iotivity/base/OcDeviceInfo.java
android/android_api/base/src/main/java/org/iotivity/base/OcDirectPairDevice.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcPlatform.java
android/android_api/base/src/main/java/org/iotivity/base/OcPrmType.java [new file with mode: 0755]
android/android_api/base/src/main/java/org/iotivity/base/OcRepresentation.java
android/android_api/base/src/main/java/org/iotivity/base/OcSecureResource.java
android/android_api/base/src/main/java/org/iotivity/base/OicSecPdAcl.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/ca/CaBtPairingInterface.java
android/android_api/base/src/main/java/org/iotivity/ca/CaEdrInterface.java
android/android_api/base/src/main/java/org/iotivity/ca/CaInterface.java
android/android_api/base/src/main/java/org/iotivity/ca/CaIpInterface.java
android/android_api/base/src/main/java/org/iotivity/ca/CaLeClientInterface.java
android/android_api/base/src/main/java/org/iotivity/ca/CaNfcInterface.java
android/examples/DirectPairing/.classpath [new file with mode: 0644]
android/examples/DirectPairing/.project [new file with mode: 0644]
android/examples/DirectPairing/DirectPairing.iml [new file with mode: 0644]
android/examples/DirectPairing/build.gradle [new file with mode: 0644]
android/examples/DirectPairing/project.properties [new file with mode: 0644]
android/examples/DirectPairing/src/main/AndroidManifest.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/assets/oic_svr_db_client_directpairing.dat [new file with mode: 0644]
android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/ExpandableListAdapter.java [new file with mode: 0644]
android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/Led.java [new file with mode: 0644]
android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/MainActivity.java [new file with mode: 0644]
android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/StringConstants.java [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_down.png [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_right.png [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/drawable-hdpi/ic_launcher.png [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/drawable-mdpi/ic_launcher.png [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/drawable-xhdpi/ic_launcher.png [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/drawable-xxhdpi/ic_launcher.png [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/layout/activity_main.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/layout/custom_list_view.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/layout/group_indicator.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/layout/list_group.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/layout/list_item.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/menu/main.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/values-v11/styles.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/values-v14/styles.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/values-w820dp/dimens.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/values/dimens.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/values/strings.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/values/styles.xml [new file with mode: 0644]
android/examples/devicediscoveryclient/src/main/java/org/iotivity/base/examples/DeviceDiscoveryClient.java
android/examples/devicediscoveryserver/src/main/java/org/iotivity/base/examples/DeviceDiscoveryServer.java
android/examples/provisioningclient/src/main/assets/oic_svr_db_client.dat
android/examples/provisioningclient/src/main/assets/oic_svr_db_client.json
android/examples/provisioningclient/src/main/java/org/iotivity/base/examples/provisioningclient/ProvisioningClient.java
android/examples/settings.gradle
android/examples/simpleclient/src/main/assets/oic_svr_db_client.dat
android/examples/simpleclient/src/main/assets/oic_svr_db_client.json
android/examples/simpleserver/src/main/assets/oic_svr_db_server.dat
android/examples/simpleserver/src/main/assets/oic_svr_db_server.json
build_common/SConscript
build_common/arduino/SConscript
build_common/external_libs.scons
build_common/msys_nt/SConscript [new file with mode: 0644]
build_common/tools/UnpackAll.py
build_common/windows/SConscript
examples/OICMiddle/SConscript
examples/OICMiddle/WrapResource.h
extlibs/boost/SConscript
extlibs/cjson/cJSON.h
extlibs/gtest/SConscript
extlibs/hippomocks.scons
extlibs/sqlite3/SConscript
extlibs/timer/SConscript
extlibs/timer/timer.c
extlibs/timer/timer.h
extlibs/tinydtls/SConscript
extlibs/tinydtls/alert.h
extlibs/tinydtls/ccm.c
extlibs/tinydtls/crypto.c
extlibs/tinydtls/crypto.h
extlibs/tinydtls/debug.c
extlibs/tinydtls/debug.h
extlibs/tinydtls/dtls.c
extlibs/tinydtls/dtls.h
extlibs/tinydtls/dtls_config.h
extlibs/tinydtls/dtls_time.c
extlibs/tinydtls/dtls_time.h
extlibs/tinydtls/global.h
extlibs/tinydtls/hmac.c
extlibs/tinydtls/hmac.h
extlibs/tinydtls/netq.c
extlibs/tinydtls/netq.h
extlibs/tinydtls/numeric.h
extlibs/tinydtls/peer.c
extlibs/tinydtls/peer.h
extlibs/tinydtls/prng.h
extlibs/tinydtls/session.c
extlibs/tinydtls/session.h
extlibs/tinydtls/sha2/sha2.c
extlibs/tinydtls/sha2/sha2.h
extlibs/tinydtls/sha2/sha2prog.c
extlibs/tinydtls/sha2/sha2speed.c
extlibs/tinydtls/t_list.h
extlibs/tinydtls/tests/dtls-client.c
extlibs/tinydtls/tests/dtls-server.c
extlibs/tinydtls/tests/pcap.c
extlibs/tinydtls/tinydtls.h
extlibs/tinydtls/utlist.h
gbsbuild.sh
plugins/SConscript
plugins/samples/linux/IotivityandZigbeeServer.c
plugins/src/SConscript
plugins/zigbee_wrapper/src/SConscript
plugins/zigbee_wrapper/src/zigbee_wrapper.c
plugins/zigbee_wrapper/telegesis_wrapper/src/SConscript
plugins/zigbee_wrapper/telegesis_wrapper/src/telegesis_wrapper.c
resource/SConscript
resource/c_common/SConscript
resource/c_common/ocrandom/include/ocrandom.h
resource/c_common/ocrandom/src/ocrandom.c
resource/c_common/oic_time/include/oic_time.h
resource/c_common/oic_time/src/oic_time.c
resource/c_common/platform_features.h
resource/c_common/windows/SConscript [new file with mode: 0644]
resource/c_common/windows/include/getopt.h [new file with mode: 0644]
resource/c_common/windows/include/pthread_create.h [new file with mode: 0644]
resource/c_common/windows/include/vs12_snprintf.h [new file with mode: 0644]
resource/c_common/windows/include/win_sleep.h [new file with mode: 0644]
resource/c_common/windows/src/getopt.c [new file with mode: 0644]
resource/c_common/windows/src/pthread_create.c [new file with mode: 0644]
resource/c_common/windows/src/snprintf.c [new file with mode: 0644]
resource/c_common/windows/src/win_sleep.c [new file with mode: 0644]
resource/csdk/SConscript
resource/csdk/connectivity/SConscript
resource/csdk/connectivity/api/cacommon.h
resource/csdk/connectivity/api/casecurityinterface.h
resource/csdk/connectivity/api/cautilinterface.h
resource/csdk/connectivity/build/SConscript
resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec
resource/csdk/connectivity/common/SConscript
resource/csdk/connectivity/common/src/camutex_noop.c
resource/csdk/connectivity/common/src/camutex_pthreads.c
resource/csdk/connectivity/common/src/cathreadpool_pthreads.c
resource/csdk/connectivity/inc/caadapternetdtls.h
resource/csdk/connectivity/inc/caadapterutils.h
resource/csdk/connectivity/inc/catcpinterface.h
resource/csdk/connectivity/inc/pkix/crypto_adapter.h
resource/csdk/connectivity/lib/libcoap-4.1.1/SConscript
resource/csdk/connectivity/lib/libcoap-4.1.1/address.h
resource/csdk/connectivity/lib/libcoap-4.1.1/async.h
resource/csdk/connectivity/lib/libcoap-4.1.1/bits.h
resource/csdk/connectivity/lib/libcoap-4.1.1/block.h
resource/csdk/connectivity/lib/libcoap-4.1.1/coap_time.h
resource/csdk/connectivity/lib/libcoap-4.1.1/config.h
resource/csdk/connectivity/lib/libcoap-4.1.1/debug.c
resource/csdk/connectivity/lib/libcoap-4.1.1/encode.h
resource/csdk/connectivity/lib/libcoap-4.1.1/net.c
resource/csdk/connectivity/lib/libcoap-4.1.1/net.h
resource/csdk/connectivity/lib/libcoap-4.1.1/option.c
resource/csdk/connectivity/lib/libcoap-4.1.1/option.h
resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.c
resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.h
resource/csdk/connectivity/lib/libcoap-4.1.1/prng.h
resource/csdk/connectivity/lib/libcoap-4.1.1/resource.c
resource/csdk/connectivity/lib/libcoap-4.1.1/resource.h
resource/csdk/connectivity/lib/libcoap-4.1.1/t_list.h
resource/csdk/connectivity/lib/libcoap-4.1.1/uri.c
resource/csdk/connectivity/lib/libcoap-4.1.1/utlist.h
resource/csdk/connectivity/src/SConscript
resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c
resource/csdk/connectivity/src/adapter_util/caadapterutils.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrserver.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrnwmonitor.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.h
resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleserver.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.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/cainterfacecontroller.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/SConscript
resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c
resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_eth.cpp
resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_wifi.cpp
resource/csdk/connectivity/src/ip_adapter/caipadapter.c
resource/csdk/connectivity/src/ip_adapter/caipserver.c
resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c
resource/csdk/connectivity/src/ip_adapter/windows/SConscript [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/windows/caipnwmonitor.c [new file with mode: 0644]
resource/csdk/connectivity/src/nfc_adapter/android/canfcserver.c
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/ca_api_unittest.cpp
resource/csdk/connectivity/test/cablocktransfertest.cpp
resource/csdk/connectivity/test/camutex_tests.cpp
resource/csdk/connectivity/test/catests.cpp
resource/csdk/connectivity/util/inc/camanagerleinterface.h
resource/csdk/connectivity/util/src/btpairing/android/cabtpairing.c
resource/csdk/connectivity/util/src/camanager/android/caleconnectionmanager.c
resource/csdk/connectivity/util/src/cautilinterface.c
resource/csdk/logger/SConscript
resource/csdk/logger/include/logger.h
resource/csdk/logger/src/logger.c
resource/csdk/routing/src/routingutility.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/directpairing.h
resource/csdk/security/include/internal/srmresourcestrings.h
resource/csdk/security/include/securevirtualresourcetypes.h
resource/csdk/security/provisioning/SConscript
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat [changed mode: 0755->0644]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.json [changed mode: 0755->0644]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat [changed mode: 0755->0644]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.json [changed mode: 0755->0644]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat [changed mode: 0755->0644]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.json [changed mode: 0755->0644]
resource/csdk/security/provisioning/ck_manager/sample/provisioningclient.c
resource/csdk/security/provisioning/ck_manager/unittest/SConscript
resource/csdk/security/provisioning/ck_manager/unittest/ckm_info_test.cpp [new file with mode: 0644]
resource/csdk/security/provisioning/ck_manager/unittest/crl_generator_test.cpp [new file with mode: 0644]
resource/csdk/security/provisioning/ck_manager/unittest/csr_generator_test.cpp [new file with mode: 0644]
resource/csdk/security/provisioning/ck_manager/unittest/pki_test.cpp
resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat
resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.json
resource/csdk/security/provisioning/include/internal/credentialgenerator.h
resource/csdk/security/provisioning/include/internal/secureresourceprovider.h
resource/csdk/security/provisioning/include/ocprovisioningmanager.h
resource/csdk/security/provisioning/include/pmtypes.h
resource/csdk/security/provisioning/sample/SConscript
resource/csdk/security/provisioning/sample/oic_svr_db_client.dat
resource/csdk/security/provisioning/sample/oic_svr_db_client.json
resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.dat
resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.json
resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat
resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.json [changed mode: 0755->0644]
resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat
resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.json
resource/csdk/security/provisioning/sample/provisioningclient.c
resource/csdk/security/provisioning/sample/sampleserver_justworks.cpp
resource/csdk/security/provisioning/sample/sampleserver_randompin.cpp
resource/csdk/security/provisioning/src/credentialgenerator.c
resource/csdk/security/provisioning/src/ocprovisioningmanager.c
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/credentialgeneratortest.cpp [new file with mode: 0644]
resource/csdk/security/provisioning/unittest/ocprovisioningmanager.cpp
resource/csdk/security/provisioning/unittest/otmunittest.cpp
resource/csdk/security/provisioning/unittest/sampleserver1.cpp [new file with mode: 0644]
resource/csdk/security/provisioning/unittest/sampleserver2.cpp [new file with mode: 0644]
resource/csdk/security/src/aclresource.c
resource/csdk/security/src/amaclresource.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 [changed mode: 0755->0644]
resource/csdk/security/src/iotvticalendar.c
resource/csdk/security/src/pbkdf2.c
resource/csdk/security/src/pconfresource.c
resource/csdk/security/src/policyengine.c
resource/csdk/security/src/psinterface.c
resource/csdk/security/src/pstatresource.c
resource/csdk/security/src/secureresourcemanager.c
resource/csdk/security/src/srmresourcestrings.c
resource/csdk/security/src/srmutility.c
resource/csdk/security/src/strptime.c [new file with mode: 0644]
resource/csdk/security/src/svcresource.c
resource/csdk/security/src/verresource.c
resource/csdk/security/tool/json2cbor.c
resource/csdk/security/unittest/SConscript
resource/csdk/security/unittest/aclresourcetest.cpp
resource/csdk/security/unittest/credentialresource.cpp
resource/csdk/security/unittest/crlresourcetest.cpp [new file with mode: 0644]
resource/csdk/security/unittest/directpairingtest.cpp
resource/csdk/security/unittest/iotvticalendartest.cpp
resource/csdk/security/unittest/oic_svr_db.dat
resource/csdk/security/unittest/oic_svr_db.json
resource/csdk/security/unittest/oic_svr_db_prov.dat [new file with mode: 0644]
resource/csdk/security/unittest/oic_unittest.dat
resource/csdk/security/unittest/oic_unittest.json
resource/csdk/security/unittest/oic_unittest_acl1.dat
resource/csdk/security/unittest/oic_unittest_acl1.json
resource/csdk/security/unittest/oic_unittest_default_acl.dat
resource/csdk/security/unittest/oic_unittest_default_acl.json
resource/csdk/security/unittest/policyengine.cpp
resource/csdk/security/unittest/pstatresource.cpp
resource/csdk/security/unittest/securityresourcemanager.cpp
resource/csdk/security/unittest/srmtestcommon.cpp
resource/csdk/security/unittest/srmtestcommon.h
resource/csdk/stack/include/internal/ocpayloadcbor.h
resource/csdk/stack/include/internal/ocserverrequest.h
resource/csdk/stack/include/internal/ocstackinternal.h
resource/csdk/stack/include/ocpayload.h
resource/csdk/stack/include/ocstack.h
resource/csdk/stack/include/octypes.h
resource/csdk/stack/include/payload_logging.h
resource/csdk/stack/include/rdpayload.h
resource/csdk/stack/samples/linux/SimpleClientServer/SConscript
resource/csdk/stack/samples/linux/SimpleClientServer/common.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/common.h [new file with mode: 0644]
resource/csdk/stack/samples/linux/SimpleClientServer/occlient.cpp
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/ocremoteaccessclient.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/SConscript
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/linux/secure/oic_amss_db.dat
resource/csdk/stack/samples/linux/secure/oic_amss_db.json
resource/csdk/stack/samples/linux/secure/oic_svr_db_client_devowner.dat
resource/csdk/stack/samples/linux/secure/oic_svr_db_client_devowner.json
resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat
resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.json
resource/csdk/stack/samples/linux/secure/oic_svr_db_client_nondevowner.dat
resource/csdk/stack/samples/linux/secure/oic_svr_db_client_nondevowner.json
resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat
resource/csdk/stack/samples/linux/secure/oic_svr_db_server.json
resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat
resource/csdk/stack/samples/tizen/SimpleClientServer/SConscript
resource/csdk/stack/samples/tizen/SimpleClientServer/ocserver.cpp
resource/csdk/stack/samples/tizen/SimpleClientServer/packaging/com.oic.ri.sample.spec
resource/csdk/stack/samples/tizen/build/packaging/com.oic.ri.spec
resource/csdk/stack/src/occlientcb.c
resource/csdk/stack/src/occollection.c
resource/csdk/stack/src/ocobserve.c
resource/csdk/stack/src/ocpayload.c
resource/csdk/stack/src/ocpayloadconvert.c
resource/csdk/stack/src/ocpayloadparse.c [changed mode: 0755->0644]
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/rdpayload.c
resource/csdk/stack/test/SConscript
resource/csdk/stack/test/cbortests.cpp
resource/csdk/stack/test/stacktests.cpp
resource/examples/SConscript
resource/examples/devicediscoveryserver.cpp
resource/examples/directpairingclient.cpp [new file with mode: 0644]
resource/examples/fridgeserver.cpp
resource/examples/lightserver.cpp
resource/examples/mediaserver.cpp [new file with mode: 0644]
resource/examples/oic_svr_db_client.dat
resource/examples/oic_svr_db_client.json
resource/examples/oic_svr_db_client_directpairing.dat [new file with mode: 0644]
resource/examples/oic_svr_db_client_directpairing.json [new file with mode: 0644]
resource/examples/oic_svr_db_server.dat
resource/examples/oic_svr_db_server.json
resource/examples/presenceclient.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/examples/winuiclient.cpp [new file with mode: 0644]
resource/examples/winuiclient.h [new file with mode: 0644]
resource/examples/winuiclientgui.cpp [new file with mode: 0644]
resource/include/AttributeValue.h
resource/include/CAManager.h
resource/include/IClientWrapper.h
resource/include/InProcClientWrapper.h
resource/include/OCApi.h
resource/include/OCDirectPairing.h [new file with mode: 0644]
resource/include/OCHeaderOption.h
resource/include/OCPlatform.h
resource/include/OCPlatform_impl.h
resource/include/OCProvisioningManager.h
resource/include/OCRepresentation.h
resource/include/OCResource.h
resource/include/OCResourceRequest.h
resource/include/OCResourceResponse.h
resource/include/OCUtilities.h
resource/include/OutOfProcClientWrapper.h
resource/include/ResourceInitException.h
resource/include/StringConstants.h
resource/oc_logger/SConscript
resource/oc_logger/examples/SConscript
resource/oc_logger/include/oc_log_stream.hpp
resource/provisioning/SConscript
resource/provisioning/examples/SConscript
resource/provisioning/examples/oic_svr_db_client.dat
resource/provisioning/examples/oic_svr_db_client.json
resource/provisioning/examples/provisioningclient.cpp
resource/provisioning/src/OCProvisioningManager.cpp
resource/provisioning/unittests/OCProvisioningTest.cpp
resource/src/CAManager.cpp
resource/src/InProcClientWrapper.cpp
resource/src/InProcServerWrapper.cpp
resource/src/OCApi.cpp
resource/src/OCDirectPairing.cpp [new file with mode: 0644]
resource/src/OCException.cpp
resource/src/OCPlatform.cpp
resource/src/OCPlatform_impl.cpp
resource/src/OCRepresentation.cpp
resource/src/OCResource.cpp
resource/src/SConscript
resource/third_party_libs.scons
resource/unit_tests.scons
resource/unittests/OCExceptionTest.cpp
resource/unittests/OCPlatformTest.cpp
resource/unittests/OCRepresentationEncodingTest.cpp
resource/unittests/OCResourceResponseTest.cpp
run.bat [new file with mode: 0644]
scons_script_how_to.txt
service/SConscript
service/easy-setup/enrollee/SConscript
service/easy-setup/mediator/csdk/unittests/SConscript
service/easy-setup/mediator/richsdk/SConscript
service/easy-setup/mediator/richsdk/android/jni/Android.mk
service/easy-setup/mediator/richsdk/unittests/SConscript
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/SConscript
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/SConscript
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
service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.json
service/easy-setup/sampleapp/mediator/linux/csdk_sample/SConscript
service/easy-setup/sampleapp/mediator/linux/richsdk_sample/SConscript
service/resource-container/SConscript
service/resource-container/examples/BMISensorBundle/src/BMISensor.cpp
service/resource-container/examples/BMISensorBundle/src/BMISensorResource.cpp
service/resource-container/examples/BMISensorBundle/src/inputSensors/HeightSensorApp/SConscript
service/resource-container/examples/DiscomfortIndexSensorBundle/src/DiscomfortIndexSensorResource.cpp
service/resource-container/src/Configuration.h
service/resource-container/unittests/ResourceContainerTest.cpp
service/resource-container/unittests/SConscript
service/resource-container/unittests/TestBundle/include/TestBundleActivator.h
service/resource-directory/SConscript
service/resource-directory/samples/SConscript
service/resource-directory/samples/rd_main.c
service/resource-directory/src/internal/rd_storage.c
service/resource-directory/src/rd_client.c
service/resource-directory/src/rd_server.c
service/resource-encapsulation/SConscript
service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.dat
service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.json
service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.dat
service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.json
service/resource-encapsulation/include/RCSException.h
service/resource-encapsulation/include/RCSResourceAttributes.h
service/resource-encapsulation/include/RCSResourceObject.h
service/resource-encapsulation/src/common/SConscript
service/resource-encapsulation/src/resourceBroker/unittest/SConscript
service/resource-encapsulation/src/resourceCache/unittests/SConscript
service/resource-encapsulation/src/serverBuilder/SConscript
service/resource-encapsulation/src/serverBuilder/src/RCSResourceObject.cpp
service/resource-encapsulation/unittests/SConscript
service/resource-hosting/SConscript
service/resource-hosting/src/HostingObject.h
service/resource-hosting/unittest/SConscript
service/scene-manager/SConscript
service/scene-manager/unittests/SConscript
service/simulator/examples/client/simulator_client.cpp
service/things-manager/SConscript
service/things-manager/sdk/inc/ActionSet.h
service/things-manager/sdk/java/jni/SConscript
service/things-manager/sdk/src/GroupManager.cpp
service/things-manager/unittests/SConscript
service/third_party_libs.scons
tools/darwin/mkfwk_ios.sh
tools/darwin/mkfwk_osx.sh
tools/scons/RunTest.py
tools/scons/UnpackAll.py
tools/tizen/iotivity.spec

diff --git a/.gbs.conf b/.gbs.conf
new file mode 100644 (file)
index 0000000..e35c163
--- /dev/null
+++ b/.gbs.conf
@@ -0,0 +1,4 @@
+[general]
+upstream_branch = upstream
+upstream_tag = ${upstreamversion}
+
index f132748..7d0ce16 100644 (file)
@@ -97,7 +97,7 @@ extlibs/android/sdk/android-sdk_r24.2
 extlibs/android/sdk/android-sdk-linux
 extlibs/android/sdk/android-sdk-macosx
 extlibs/android/sdk/android-sdk-windows
-extlibs/boost/boost_1_58_0
+extlibs/boost/*
 extlibs/tinycbor/tinycbor
 *.tgz
 *.zip
index 35ff720..ac76f39 100644 (file)
@@ -56,7 +56,7 @@ build_dir = env.get('BUILD_DIR')
 # Build 'resource' sub-project
 SConscript(build_dir + 'resource/SConscript')
 
-if target_os not in ['arduino','darwin','ios', 'android']:
+if target_os not in ['arduino','darwin','ios', 'android', 'msys_nt', 'windows']:
        SConscript(build_dir + 'examples/OICMiddle/SConscript')
 
 # Build 'service' sub-project
@@ -76,6 +76,6 @@ env.PrintTargets()
 if target_os == 'arduino':
        env.UploadHelp()
 
-# to install the generated pc file into custome prefix location
+# to install the generated pc file into custom prefix location
 env.UserInstallTargetPCFile('iotivity.pc', 'iotivity.pc')
 
index 3e67020..834a82f 100755 (executable)
@@ -41,7 +41,7 @@ android {
         minSdkVersion 21\r
         targetSdkVersion 21\r
         versionCode 1\r
-        versionName "1.1"\r
+        versionName "1.1.1"\r
         buildConfigField 'int', 'SECURED', SECURED\r
     }\r
     buildTypes {\r
index cc43275..a513cb1 100644 (file)
@@ -58,7 +58,7 @@ LOCAL_SRC_FILES :=  JniOcStack.cpp \
                     JniEntityHandler.cpp \\r
                     JniOnResourceFoundListener.cpp \\r
                     JniOnDeviceInfoListener.cpp \\r
-                   JniOnPlatformInfoListener.cpp \\r
+                    JniOnPlatformInfoListener.cpp \\r
                     JniOnPresenceListener.cpp \\r
                     JniOnGetListener.cpp \\r
                     JniOnPutListener.cpp \\r
@@ -74,15 +74,18 @@ LOCAL_SRC_FILES :=  JniOcStack.cpp \
                     JniOcPlatform.cpp \\r
                     JniOcResource.cpp \\r
                     JniOcResourceIdentifier.cpp \\r
-                    JniOcSecurity.cpp\r
+                    JniOcSecurity.cpp \\r
+                    JniOnDPDevicesFoundListener.cpp \\r
+                    JniOnDirectPairingListener.cpp \\r
+                    JniOcDirectPairDevice.cpp\r
 ifeq ($(SECURED), 1)\r
-LOCAL_SRC_FILES +=  JniOcSecureResource.cpp \\r
-                    JniOcProvisioning.cpp \\r
-                    JniSecureUtils.cpp \\r
-                    JniProvisionResultListner.cpp \\r
-                    JniPinCheckListener.cpp \\r
-                    JniDisplayPinListener.cpp\r
-endif\r
+    LOCAL_SRC_FILES +=  JniOcSecureResource.cpp \\r
+                        JniOcProvisioning.cpp \\r
+                        JniSecureUtils.cpp \\r
+                        JniProvisionResultListner.cpp \\r
+                        JniPinCheckListener.cpp \\r
+                        JniDisplayPinListener.cpp\r
+                        endif\r
 \r
 LOCAL_LDLIBS := -llog\r
 LOCAL_STATIC_LIBRARIES := android-oc\r
index d641f3d..e8649ec 100644 (file)
@@ -74,7 +74,7 @@ void CAManagerConnectionStateChangedCB(CATransportAdapter_t adapter,
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -155,7 +155,7 @@ void CAManagerAdapterStateChangedCB(CATransportAdapter_t adapter, bool enabled)
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -329,3 +329,14 @@ Java_org_iotivity_ca_CaInterface_caBtPairingCreateBond(JNIEnv *env, jclass clazz
     (void)clazz;
     CAUtilCreateBond(env, device);
 }
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_setLeScanIntervalTimeImpl(JNIEnv *env, jclass clazz,
+                                                           jint intervalTime, jint workignCount)
+{
+    LOGI("setLeScanIntervalTimeImpl");
+    (void)env;
+    (void)clazz;
+    CAUtilSetLEScanInterval(intervalTime, workignCount);
+}
+
index 20dc995..9861eb8 100644 (file)
@@ -121,6 +121,14 @@ extern "C" {
     JNIEXPORT void JNICALL Java_org_iotivity_ca_CaInterface_initialize
         (JNIEnv *, jclass, jobject, jobject);
 
+    /*
+     * Class:     Java_org_iotivity_ca_CaInterface_setLeScanIntervalTimeImpl
+     * Method:    setLeScanIntervalTimeImpl
+     * Signature: (II)V
+     */
+    JNIEXPORT void JNICALL Java_org_iotivity_ca_CaInterface_setLeScanIntervalTimeImpl
+        (JNIEnv *, jclass, jint, jint);
+
 #ifdef __cplusplus
 }
 #endif
index 25ee926..1705bdf 100644 (file)
@@ -33,7 +33,7 @@ JniDisplayPinListener::~JniDisplayPinListener()
     LOGI("~JniDisplayPinListener()");
     if (m_jgListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
         if (NULL == env) return;
         env->DeleteGlobalRef(m_jgListener);
@@ -43,9 +43,12 @@ JniDisplayPinListener::~JniDisplayPinListener()
 
 void JniDisplayPinListener::displayPinCallback(char *pinBuf, size_t pinSize)
 {
-    jint ret;
+    jint ret = JNI_ERR;
     JNIEnv *env = GetJNIEnv(ret);
-    if (NULL == env) return;
+    if (NULL == env)
+    {
+        return;
+    }
 
     jclass clsL = env->GetObjectClass(m_jgListener);
 
index 1d641ae..f46dde0 100644 (file)
@@ -33,7 +33,7 @@ JniEntityHandler::~JniEntityHandler()
     LOGD("~JniEntityHandler");
     if (m_jListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
         if (nullptr == env)
         {
@@ -54,7 +54,7 @@ OCEntityHandlerResult JniEntityHandler::handleEntity(
     const std::shared_ptr<OCResourceRequest> request)
 {
     LOGD("JniEntityHandler_handleEntity");
-    jint envRet;
+    jint envRet = JNI_ERR;
     JNIEnv *env = GetJNIEnv(envRet);
     if (nullptr == env)
     {
@@ -133,7 +133,10 @@ OCEntityHandlerResult JniEntityHandler::handleEntity(
     jmethodID getValue_ID = env->GetMethodID(clsResult, "getValue", "()I");
     if (!getValue_ID)
     {
-        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == envRet)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return OC_EH_ERROR;
     }
     jint jResult = env->CallIntMethod(entityHandlerResult, getValue_ID);
index b082f7d..989dd3d 100644 (file)
@@ -51,6 +51,7 @@ public:
                 break;
             }
         }
+
         if (!onEventListener)
         {
             onEventListener = new T(env, jListener, owner);
@@ -66,9 +67,11 @@ public:
             {
                 LOGD("OnEventListener: Failed to create global listener ref.");
                 delete onEventListener;
+                return nullptr;
             }
             LOGD("OnEventListener: new listener");
         }
+
         m_mapMutex.unlock();
         return onEventListener;
     }
diff --git a/android/android_api/base/jni/JniOcDirectPairDevice.cpp b/android/android_api/base/jni/JniOcDirectPairDevice.cpp
new file mode 100644 (file)
index 0000000..ff4e626
--- /dev/null
@@ -0,0 +1,145 @@
+/*
+* //******************************************************************
+* //
+* // 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 "JniOcDirectPairDevice.h"
+#include "OCDirectPairing.h"
+#include "OCDirectPairing.h"
+using namespace OC;
+namespace PH = std::placeholders;
+
+JniOcDirectPairDevice::JniOcDirectPairDevice(std::shared_ptr<OC::OCDirectPairing> directPairingDevice)
+    : m_sharedDirectPairDevice(directPairingDevice)
+{
+}
+
+JniOcDirectPairDevice::~JniOcDirectPairDevice()
+{
+    LOGD("~JniOcDirectPairDevice()");
+    m_sharedDirectPairDevice = nullptr;
+}
+
+std::string JniOcDirectPairDevice::getHost()
+{
+   return m_sharedDirectPairDevice->getHost();
+}
+
+std::vector<OCPrm_t> JniOcDirectPairDevice::getPairingMethods()
+{
+
+   return m_sharedDirectPairDevice->getPairingMethods();
+}
+
+OCConnectivityType JniOcDirectPairDevice::connectivityType()
+{
+    return m_sharedDirectPairDevice->getConnType();
+}
+
+JniOcDirectPairDevice* JniOcDirectPairDevice::getJniOcDirectPairDevicePtr(JNIEnv *env, jobject thiz)
+{
+    JniOcDirectPairDevice *dpDev = GetHandle<JniOcDirectPairDevice>(env, thiz);
+    if (env->ExceptionCheck())
+    {
+        LOGE("Failed to get native handle from OcDirectPairingDevice");
+    }
+    if (!dpDev)
+    {
+        ThrowOcException(JNI_NO_NATIVE_POINTER, "");
+    }
+    return dpDev;
+}
+std::shared_ptr<OC::OCDirectPairing> JniOcDirectPairDevice::getPtr()
+{
+    return m_sharedDirectPairDevice;
+}
+
+JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcDirectPairDevice_getHost
+(JNIEnv *env, jobject thiz)
+{
+
+    LOGD("OcDirectPairing_getHost");
+
+    JniOcDirectPairDevice* device = JniOcDirectPairDevice::getJniOcDirectPairDevicePtr(env,thiz);
+    if (!device)
+    {
+        return nullptr;
+    }
+
+    std::string dev  = device->getHost();
+    return env->NewStringUTF(dev.c_str());
+}
+
+JNIEXPORT jintArray JNICALL Java_org_iotivity_base_OcDirectPairDevice_getPairingMethods
+        (JNIEnv *env, jobject thiz)
+{
+
+    LOGD("OcDirectPairing_getPairingMethods");
+
+    std::vector<jint> pairingMethodList;
+    JniOcDirectPairDevice* device = JniOcDirectPairDevice::getJniOcDirectPairDevicePtr(env,thiz);
+    if (!device)
+    {
+        return nullptr;
+    }
+
+    std::vector<OCPrm_t> pairingMethods = device->getPairingMethods();
+    return JniOcDirectPairDevice::JconvertIntVectorToJavaList(env,pairingMethods);
+}
+
+
+jintArray JniOcDirectPairDevice::JconvertIntVectorToJavaList(JNIEnv *env, std::vector<OCPrm_t> &vector)
+{
+
+    jsize len = static_cast<jsize>(vector.size());
+
+    jintArray intArray = env->NewIntArray(len);
+    if (!intArray)
+    {
+        return nullptr;
+    }
+
+    env->SetIntArrayRegion(intArray, (jsize)0, len, (const jint*)&vector[0]);
+
+    if (env->ExceptionCheck())
+    {
+        LOGE("ArrayIndexOutOfBoundsException in  JconvertIntVectorToJavaList");
+    }
+    return intArray;
+}
+
+/*
+* Class:     org_iotivity_base_OcDirectPairDevice
+* Method:    getConnectivityTypeN
+* Signature: ()I
+*/
+JNIEXPORT jint JNICALL Java_org_iotivity_base_OcDirectPairDevice_getConnectivityTypeN
+(JNIEnv *env, jobject thiz)
+{
+    LOGD("OcDirectPairDevice_getConnectivityType");
+    JniOcDirectPairDevice* device = JniOcDirectPairDevice::getJniOcDirectPairDevicePtr(env,thiz);
+    if (!device)
+    {
+        return -1;
+    }
+
+    OCConnectivityType connectivityType = device->connectivityType();
+    return static_cast<jint>(connectivityType);
+}
diff --git a/android/android_api/base/jni/JniOcDirectPairDevice.h b/android/android_api/base/jni/JniOcDirectPairDevice.h
new file mode 100644 (file)
index 0000000..505bac2
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+* //******************************************************************
+* //
+* // 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 "JniOcStack.h"
+#include "JniOnDPDevicesFoundListener.h"
+#include "OCDirectPairing.h"
+#include <mutex>
+
+#ifndef _Included_org_iotivity_base_OcDirectPairDevice
+#define _Included_org_iotivity_base_OcDirectPairDevice
+
+using namespace OC;
+
+class JniOcDirectPairDevice
+{
+    public:
+        JniOcDirectPairDevice(std::shared_ptr<OCDirectPairing> directPairingDevice);
+        ~JniOcDirectPairDevice();
+
+        static JniOcDirectPairDevice* getJniOcDirectPairDevicePtr(JNIEnv *env, jobject thiz);
+        static jintArray JconvertIntVectorToJavaList(JNIEnv *env, std::vector<OCPrm_t> &vector);
+
+        std::shared_ptr<OCDirectPairing> getPtr();
+        std::string getHost();
+        std::vector<OCPrm_t> getPairingMethods();
+        OCConnectivityType connectivityType();
+
+    private:
+          std::shared_ptr<OCDirectPairing> m_sharedDirectPairDevice;
+};
+
+/* DO NOT EDIT THIS FILE BEYOND THIS LINE - it is machine generated */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+    /*
+     * Class:     org_iotivity_base_OcDirectPairDevice
+     * Method:    getDirectPairedDevices
+     * Signature: (Lorg/iotivity/base/OcDirectPairDevice/GetDirectPairedListener;)V
+     */
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcDirectPairDevice_getDirectPairedDevices
+        (JNIEnv *, jobject, jobject);
+
+   /*
+    * Class:     org_iotivity_base_OcDirectPairDevice
+    * Method:    getHost
+    * Signature: ()Ljava/lang/String;
+    */
+    JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcDirectPairDevice_getHost
+        (JNIEnv *, jobject);
+
+    /*
+     * Class:     org_iotivity_base_OcDirectPairDevice
+     * Method:    getPairingMethods
+     * Signature: ()Ljava/util/List;
+     */
+    JNIEXPORT jintArray JNICALL Java_org_iotivity_base_OcDirectPairDevice_getPairingMethods
+        (JNIEnv *, jobject);
+
+    /*
+     * Class:     org_iotivity_base_OcDirectPairDevice
+     * Method:    doDirectPairing
+     * Signature: (Lorg/iotivity/base/OcDirectPairDevice;Lorg/iotivity/base/OcPrmType;
+     *           Ljava/lang/String;Lorg/iotivity/base/OcDirectPairDevice/DirectPairingListener;)V
+     */
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcDirectPairDevice_doDirectPairing
+        (JNIEnv *, jobject, jobject, jint, jstring, jobject);
+
+    /*
+    * Class:     org_iotivity_base_OcDirectPairDevice
+    * Method:    getConnectivityTypeN
+    * Signature: ()I
+    */
+    JNIEXPORT jint JNICALL Java_org_iotivity_base_OcDirectPairDevice_getConnectivityTypeN
+        (JNIEnv *env, jobject thiz);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
+
index 93029c9..5678341 100644 (file)
@@ -25,7 +25,9 @@
 #include "JniOcPresenceHandle.h"
 #include "JniOcResourceResponse.h"
 #include "JniOcSecurity.h"
+#include "JniOcDirectPairDevice.h"
 #include "JniUtils.h"
+#include "ocpayload.h"
 
 using namespace OC;
 
@@ -320,6 +322,148 @@ void RemoveOnPresenceListener(JNIEnv* env, jobject jListener)
     presenceMapLock.unlock();
 }
 
+JniOnDPDevicesFoundListener* AddOnDPDevicesFoundListener(JNIEnv* env, jobject jListener)
+{
+    JniOnDPDevicesFoundListener *onDPDeviceListener = nullptr;
+
+    dpDevicesFoundListenerMapLock.lock();
+
+    for (auto it = onDPDevicesFoundListenerMap.begin(); it !=
+            onDPDevicesFoundListenerMap.end(); ++it)
+    {
+        if (env->IsSameObject(jListener, it->first))
+        {
+            auto refPair = it->second;
+            onDPDeviceListener = refPair.first;
+            refPair.second++;
+            it->second = refPair;
+            onDPDevicesFoundListenerMap.insert(*it);
+            LOGD("onDPDeviceListener: ref. count incremented");
+            break;
+        }
+    }
+    if (!onDPDeviceListener)
+    {
+        onDPDeviceListener = new JniOnDPDevicesFoundListener(env, jListener,
+                RemoveOnDPDevicesFoundListener);
+        jobject jgListener = env->NewGlobalRef(jListener);
+        onDPDevicesFoundListenerMap.insert(
+                std::pair<jobject, std::pair<JniOnDPDevicesFoundListener*, int>>(
+                    jgListener,
+                    std::pair<JniOnDPDevicesFoundListener*, int>(onDPDeviceListener, 1)));
+        LOGI("onDPDeviceListener: new listener");
+    }
+    dpDevicesFoundListenerMapLock.unlock();
+    return onDPDeviceListener;
+}
+
+void RemoveOnDPDevicesFoundListener(JNIEnv* env, jobject jListener)
+{
+    dpDevicesFoundListenerMapLock.lock();
+    bool isFound = false;
+    for (auto it = onDPDevicesFoundListenerMap.begin(); it !=
+            onDPDevicesFoundListenerMap.end(); ++it)
+    {
+        if (env->IsSameObject(jListener, it->first))
+        {
+            auto refPair = it->second;
+            if (refPair.second > 1)
+            {
+                refPair.second--;
+                it->second = refPair;
+                onDPDevicesFoundListenerMap.insert(*it);
+                LOGI("onDPDeviceListener: ref. count decremented");
+            }
+            else
+            {
+                env->DeleteGlobalRef(it->first);
+                JniOnDPDevicesFoundListener* listener = refPair.first;
+                delete listener;
+                onDPDevicesFoundListenerMap.erase(it);
+                LOGI("onDPDeviceListener is removed");
+            }
+            isFound = true;
+            break;
+        }
+    }
+    if (!isFound)
+    {
+        ThrowOcException(JNI_EXCEPTION, "onDPDeviceListener not found");
+    }
+    dpDevicesFoundListenerMapLock.unlock();
+}
+
+JniOnDirectPairingListener* AddOnDirectPairingListener(JNIEnv* env, jobject jListener)
+{
+    JniOnDirectPairingListener *onDirectPairingListener = nullptr;
+
+    directPairingListenerMapLock.lock();
+
+    for (auto it = directPairingListenerMap.begin(); it !=
+            directPairingListenerMap.end(); ++it)
+    {
+        if (env->IsSameObject(jListener, it->first))
+        {
+            auto refPair = it->second;
+            onDirectPairingListener = refPair.first;
+            refPair.second++;
+            it->second = refPair;
+            directPairingListenerMap.insert(*it);
+            LOGD("onDirectPairingListener: ref. count incremented");
+            break;
+        }
+    }
+    if (!onDirectPairingListener)
+    {
+        onDirectPairingListener = new JniOnDirectPairingListener(env, jListener,
+                RemoveOnDirectPairingListener);
+        jobject jgListener = env->NewGlobalRef(jListener);
+        directPairingListenerMap.insert(
+                std::pair<jobject, std::pair<JniOnDirectPairingListener*, int>>(
+                    jgListener,
+                    std::pair<JniOnDirectPairingListener*, int>(onDirectPairingListener, 1)));
+        LOGI("onDirectPairingListener: new listener");
+    }
+    directPairingListenerMapLock.unlock();
+    return onDirectPairingListener;
+}
+
+void RemoveOnDirectPairingListener(JNIEnv* env, jobject jListener)
+{
+    directPairingListenerMapLock.lock();
+    bool isFound = false;
+    for (auto it = directPairingListenerMap.begin(); it !=
+            directPairingListenerMap.end(); ++it)
+    {
+        if (env->IsSameObject(jListener, it->first))
+        {
+            auto refPair = it->second;
+            if (refPair.second > 1)
+            {
+                refPair.second--;
+                it->second = refPair;
+                directPairingListenerMap.insert(*it);
+                LOGI("onDirectPairingListener: ref. count decremented");
+            }
+            else
+            {
+                env->DeleteGlobalRef(it->first);
+                JniOnDirectPairingListener* listener = refPair.first;
+                delete listener;
+                directPairingListenerMap.erase(it);
+                LOGI("onDirectPairingListener is removed");
+            }
+            isFound = true;
+            break;
+        }
+    }
+    if (!isFound)
+    {
+        ThrowOcException(JNI_EXCEPTION, "onDirectPairingListener not found");
+    }
+    directPairingListenerMapLock.unlock();
+}
+
 /*
 * Class:     org_iotivity_base_OcPlatform
 * Method:    configure
@@ -376,7 +520,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyAllObservers0
 
     JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(
         env, jResourceHandle);
-    if (!jniOcResourceHandle) return;
+    if (!jniOcResourceHandle)
+    {
+        return;
+    }
 
     try
     {
@@ -419,7 +566,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyAllObservers1
         return;
     }
 
-    try{
+    try {
         OCStackResult result = OCPlatform::notifyAllObservers(
             jniOcResourceHandle->getOCResourceHandle(),
             JniUtils::getQOS(env, static_cast<int>(jQoS)));
@@ -703,6 +850,145 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_findResource1(
 }
 
 /*
+ * Class:     org_iotivity_base_OcPlatform
+ * Method:    findDirectPairingDevices
+ * Signature: (ILorg/iotivity/base/OcPlatform/FindDirectPairingListener;)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_findDirectPairingDevices
+  (JNIEnv * env, jclass clazz, jint jTimeout, jobject jListener)
+{
+    LOGD("OcPlatform_findDirectPairingDevices");
+
+    if (!jListener)
+    {
+        ThrowOcException(OC_STACK_INVALID_PARAM, "onDPDevicesFoundListener cannot be null");
+        return;
+    }
+    JniOnDPDevicesFoundListener *onDPDevsFoundListener = AddOnDPDevicesFoundListener(env,
+            jListener);
+
+    GetDirectPairedCallback getDirectPairedCallback =
+        [onDPDevsFoundListener](PairedDevices pairingDevList)
+        {
+            onDPDevsFoundListener->directPairingDevicesCallback(pairingDevList,
+                    DPFunc::FIND_DIRECT_PAIRED_DEV_LIST);
+        };
+
+    try
+    {
+        OCStackResult result = OCPlatform::findDirectPairingDevices(jTimeout,
+                getDirectPairedCallback);
+        if (OC_STACK_OK != result)
+        {
+            ThrowOcException(result, "OCPlatform::findDirectPairingDevices has failed");
+            return;
+        }
+    }
+    catch (OCException& e)
+    {
+        LOGE("%s", e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
+    }
+}
+
+/*
+ * Class:     org_iotivity_base_OcPlatform
+ * Method:    getDirectPairedDevices
+ * Signature: (Lorg/iotivity/base/OcDirectPairDevice/GetDirectPairedListener;)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getDirectPairedDevices
+(JNIEnv *env, jclass jclazz, jobject jListener)
+{
+    LOGD("OcPlatform_getDirectPairedDevices");
+
+    if (!jListener)
+    {
+        ThrowOcException(OC_STACK_INVALID_PARAM, "getPairedDevList Callback cannot be null");
+        return;
+    }
+    JniOnDPDevicesFoundListener *onGetPairedDevicesListener = AddOnDPDevicesFoundListener(env,
+            jListener);
+
+    GetDirectPairedCallback getDirectPairedCallback =
+        [onGetPairedDevicesListener](PairedDevices pairedDevList)
+        {
+            onGetPairedDevicesListener->directPairingDevicesCallback(pairedDevList,
+                    DPFunc::GET_PAIRED_DEV_LIST);
+        };
+
+    try
+    {
+        OCStackResult result = OCPlatform::getDirectPairedDevices(getDirectPairedCallback);
+        if (OC_STACK_OK != result)
+        {
+            ThrowOcException(result, "OcDirectPairDevice_getDirectPairedDevices");
+            return;
+        }
+    }
+    catch (OCException& e)
+    {
+        LOGE("%s", e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
+    }
+}
+
+/*
+ * Class:     org_iotivity_base_OcPlatform
+ * Method:    doDirectPairing
+ * Signature: (Lorg/iotivity/base/OcDirectPairDevice;Lorg/iotivity/base/OcPrmType;
+ *           Ljava/lang/String;Lorg/iotivity/base/OcDirectPairDevice/DirectPairingListener;)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_doDirectPairing0
+(JNIEnv *env, jclass clazz, jobject jpeer, jint jprmType, jstring jpin, jobject jListener)
+{
+    LOGD("OcPlatform_doDirectPairing");
+
+    if (!jListener)
+    {
+        ThrowOcException(OC_STACK_INVALID_PARAM, "doDirectPairing Callback cannot be null");
+        return;
+    }
+    if (!jpeer)
+    {
+        ThrowOcException(OC_STACK_INVALID_PARAM, "Peer cannot be null");
+        return;
+    }
+
+    JniOnDirectPairingListener *onDirectPairingListener = AddOnDirectPairingListener(env,
+            jListener);
+
+    DirectPairingCallback DirectPairingCB =
+        [onDirectPairingListener](std::shared_ptr<OCDirectPairing> dpDev, OCStackResult result)
+        {
+            onDirectPairingListener->doDirectPairingCB(dpDev, result);
+        };
+
+    JniOcDirectPairDevice *dev = JniOcDirectPairDevice::getJniOcDirectPairDevicePtr(env, jpeer);
+
+    if (!dev)
+    {
+        return ;
+    }
+    std::string pin = env->GetStringUTFChars(jpin, 0);
+
+    try
+    {
+        OCStackResult result = OCPlatform::doDirectPairing(dev->getPtr(), (OCPrm_t)jprmType,
+                pin, DirectPairingCB);
+        if (OC_STACK_OK != result)
+        {
+            ThrowOcException(result, "OcPlatform_oDirectPairing");
+            return;
+        }
+    }
+    catch (OCException& e)
+    {
+        LOGE("%s", e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
+    }
+}
+
+/*
 * Class:     org_iotivity_base_OcPlatform
 * Method:    getDeviceInfo0
 * Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnDeviceFoundListener;)V
@@ -949,7 +1235,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_registerResource0(
         return nullptr;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, jResource);
-    if (!resource) return nullptr;
+    if (!resource)
+    {
+        return nullptr;
+    }
 
     OCResourceHandle resourceHandle;
     try
@@ -1070,20 +1359,49 @@ jobject jListener, jint jResourceProperty)
 JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_registerDeviceInfo0(
     JNIEnv *env,
     jclass clazz,
-    jstring jDeviceName)
+    jstring jDeviceName,
+    jobjectArray jDeviceTypes)
 {
     LOGI("OcPlatform_registerDeviceInfo");
 
-    std::string deviceName;
-    if (jDeviceName)
+    if (!jDeviceName)
+    {
+        ThrowOcException(OC_STACK_INVALID_PARAM, "deviceName cannot be null");
+        return;
+    }
+
+    if (!jDeviceTypes)
     {
-        deviceName = env->GetStringUTFChars(jDeviceName, nullptr);
+        ThrowOcException(OC_STACK_INVALID_PARAM, "deviceTypes cannot be null");
+        return;
     }
 
     OCDeviceInfo deviceInfo;
     try
     {
-        DuplicateString(&deviceInfo.deviceName, deviceName);
+        DuplicateString(&deviceInfo.deviceName, env->GetStringUTFChars(jDeviceName, nullptr));
+        deviceInfo.types = NULL;
+
+        jsize len = env->GetArrayLength(jDeviceTypes);
+        for (jsize i = 0; i < len; ++i)
+        {
+            jstring jStr = (jstring)env->GetObjectArrayElement(jDeviceTypes, i);
+            if (!jStr)
+            {
+                delete deviceInfo.deviceName;
+                ThrowOcException(OC_STACK_INVALID_PARAM, "device type cannot be null");
+                return;
+            }
+
+            OCResourcePayloadAddStringLL(&deviceInfo.types, env->GetStringUTFChars(jStr, nullptr));
+            if (env->ExceptionCheck())
+            {
+                delete deviceInfo.deviceName;
+                return;
+            }
+
+            env->DeleteLocalRef(jStr);
+        }
     }
     catch (std::exception &e)
     {
@@ -1299,7 +1617,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindResource0
     }
     JniOcResourceHandle* jniOcResourceCollectionHandle =
         JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceCollectionHandle);
-    if (!jniOcResourceCollectionHandle) return;
+    if (!jniOcResourceCollectionHandle)
+    {
+        return;
+    }
 
     JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(
         env, jResourceHandle);
@@ -1550,7 +1871,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindTypeToResource0(
 
     JniOcResourceHandle* jniOcResourceHandle =
         JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceHandle);
-    if (!jniOcResourceHandle) return;
+    if (!jniOcResourceHandle)
+    {
+        return;
+    }
 
     try
     {
@@ -1950,7 +2274,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_sendResponse0(
 
     JniOcResourceResponse *jniResponse =
         JniOcResourceResponse::getJniOcResourceResponsePtr(env, jResourceResponse);
-    if (!jniResponse) return;
+    if (!jniResponse)
+    {
+        return;
+    }
 
     try
     {
index cfd6853..a45f059 100644 (file)
@@ -23,6 +23,8 @@
 #include "JniOnResourceFoundListener.h"
 #include "JniOnDeviceInfoListener.h"
 #include "JniOnPlatformInfoListener.h"
+#include "JniOnDPDevicesFoundListener.h"
+#include "JniOnDirectPairingListener.h"
 #include "JniOnPresenceListener.h"
 #include <mutex>
 
@@ -43,15 +45,26 @@ void RemoveOnPlatformInfoListener(JNIEnv* env, jobject jListener);
 JniOnPresenceListener* AddOnPresenceListener(JNIEnv* env, jobject jListener);
 void RemoveOnPresenceListener(JNIEnv* env, jobject jListener);
 
+JniOnDPDevicesFoundListener* AddOnDPDevicesFoundListener(JNIEnv* env, jobject jListener);
+void RemoveOnDPDevicesFoundListener(JNIEnv* env, jobject jListener);
+
+JniOnDirectPairingListener* AddOnDirectPairingListener(JNIEnv* env, jobject jListener);
+void RemoveOnDirectPairingListener(JNIEnv* env, jobject jListener);
+
+
 std::map<jobject, std::pair<JniOnResourceFoundListener*, int>> onResourceFoundListenerMap;
 std::map<jobject, std::pair<JniOnDeviceInfoListener*, int>> onDeviceInfoListenerMap;
 std::map<jobject, std::pair<JniOnPlatformInfoListener*, int>> onPlatformInfoListenerMap;
 std::map<jobject, std::pair<JniOnPresenceListener*, int>> onPresenceListenerMap;
+std::map<jobject, std::pair<JniOnDPDevicesFoundListener*, int>> onDPDevicesFoundListenerMap;
+std::map<jobject, std::pair<JniOnDirectPairingListener*, int>> directPairingListenerMap;
 
 std::mutex resourceFoundMapLock;
 std::mutex deviceInfoMapLock;
 std::mutex platformInfoMapLock;
 std::mutex presenceMapLock;
+std::mutex dpDevicesFoundListenerMapLock;
+std::mutex directPairingListenerMapLock;
 
 #ifdef __cplusplus
 extern "C" {
@@ -163,10 +176,10 @@ extern "C" {
     /*
     * Class:     org_iotivity_base_OcPlatform
     * Method:    registerDeviceInfo0
-    * Signature: (Ljava/lang/String;)V
+    * Signature: (Ljava/lang/String;[Ljava/lang/String;)V
     */
     JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_registerDeviceInfo0
-        (JNIEnv *, jclass, jstring);
+        (JNIEnv *, jclass, jstring, jobjectArray);
 
     /*
     * Class:     org_iotivity_base_OcPlatform
@@ -288,6 +301,30 @@ extern "C" {
     JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_sendResponse0
         (JNIEnv *, jclass, jobject);
 
+    /*
+     * Class:     org_iotivity_base_OcPlatform
+     * Method:    findDirectPairingDevices
+     * Signature: (ILorg/iotivity/base/OcPlatform/FindDirectPairingListener;)V
+     */
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_findDirectPairingDevices
+        (JNIEnv *, jclass, jint, jobject);
+
+    /*
+     * Class:     org_iotivity_base_OcPlatform
+     * Method:    getDirectPairedDevices
+     * Signature: (Lorg/iotivity/base/OcDirectPairDevice/GetDirectPairedListener;)V
+     */
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getDirectPairedDevices
+        (JNIEnv *, jclass, jobject);
+
+    /*
+     * Class:     org_iotivity_base_OcPlatform
+     * Method:    doDirectPairing
+     * Signature: (Lorg/iotivity/base/OcDirectPairDevice;Lorg/iotivity/base/OcPrmType;
+     *           Ljava/lang/String;Lorg/iotivity/base/OcDirectPairDevice/DirectPairingListener;)V
+     */
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_doDirectPairing0
+        (JNIEnv *, jclass, jobject, jint, jstring, jobject);
 #ifdef __cplusplus
 }
 #endif
index 00f81a1..28b7859 100644 (file)
@@ -24,7 +24,8 @@
 
 JniOcPresenceHandle::JniOcPresenceHandle(JniOnPresenceListener* jniListener, OCPresenceHandle presenceHandle)
     : m_jniListener(jniListener), m_presenceHandle(presenceHandle)
-{}
+{
+}
 
 JniOcPresenceHandle::~JniOcPresenceHandle()
 {
@@ -70,4 +71,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPresenceHandle_dispose
     LOGD("OcPresenceHandle_dispose");
     JniOcPresenceHandle *presenceHandle = JniOcPresenceHandle::getJniOcPresenceHandlePtr(env, thiz);
     delete presenceHandle;
-}
\ No newline at end of file
+}
index c9cf0d3..042e2a4 100644 (file)
@@ -19,6 +19,9 @@
 * //
 * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 */
+
+#include <map>
+
 #include "JniOcRepresentation.h"
 #include "JniUtils.h"
 
@@ -40,6 +43,37 @@ OCRepresentation* JniOcRepresentation::getOCRepresentationPtr(JNIEnv *env, jobje
 
 /*
 * Class:     org_iotivity_base_OcRepresentation
+* Method:    getValues
+* Signature: ()Ljava/util/Map;
+*/
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getValues
+(JNIEnv *env, jobject thiz)
+{
+    LOGD("OcRepresentation_getValues");
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
+    if (!rep)
+    {
+        return nullptr;
+    }
+
+    std::map<std::string, AttributeValue> values = rep->getValues();
+    jobject jHashMap = env->NewObject(g_cls_HashMap, g_mid_HashMap_ctor);
+    if (!jHashMap)
+    {
+        return nullptr;
+    }
+
+    for (std::map<std::string, AttributeValue>::const_iterator it = values.begin(); it != values.end(); it++)
+    {
+        jobject key = static_cast<jobject>(env->NewStringUTF(it->first.c_str()));
+        jobject val = boost::apply_visitor(JObjectConverter(env), it->second);
+        env->CallObjectMethod(jHashMap, g_mid_HashMap_put, key, val);
+    }
+    return jHashMap;
+}
+
+/*
+* Class:     org_iotivity_base_OcRepresentation
 * Method:    getValueN
 * Signature: (Ljava/lang/String;)Ljava/lang/Object;
 */
@@ -53,7 +87,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getValueN
         return nullptr;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return nullptr;
+    if (!rep)
+    {
+        return nullptr;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
 
@@ -81,7 +118,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueInteger
         return;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string str = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(str, static_cast<int>(jValue));
@@ -102,7 +142,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDouble
         return;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string str = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(str, static_cast<double>(jValue));
@@ -123,7 +166,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBoolean
         return;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string str = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(str, static_cast<bool>(jValue));
@@ -144,7 +190,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueStringN
         return;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     std::string value = env->GetStringUTFChars(jValue, nullptr);
@@ -167,14 +216,20 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresent
         return;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
 
     if (jValue)
     {
         OCRepresentation *value = JniOcRepresentation::getOCRepresentationPtr(env, jValue);
-        if (!value) return;
+        if (!value)
+        {
+            return;
+        }
         rep->setValue(key, *value);
     }
     else
@@ -209,7 +264,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueIntegerAr
     env->ReleaseIntArrayElements(jValue, ints, JNI_ABORT);
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -247,7 +305,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueInteger2D
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -293,7 +354,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueInteger3D
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -325,7 +389,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDoubleArr
     env->ReleaseDoubleArrayElements(jValue, doubles, JNI_ABORT);
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -363,7 +430,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDouble2DA
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -409,7 +479,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDouble3DA
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -441,7 +514,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBooleanAr
     env->ReleaseBooleanArrayElements(jValue, booleans, JNI_ABORT);
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -480,7 +556,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBoolean2D
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -527,7 +606,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBoolean3D
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -552,7 +634,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueStringArr
     JniUtils::convertJavaStrArrToStrVector(env, jValue, value);
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -584,7 +669,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueString2DA
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -624,8 +712,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueString3DA
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
-
+    if (!rep)
+    {
+        return;
+    }
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
 }
@@ -649,7 +739,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresent
     JniUtils::convertJavaRepresentationArrToVector(env, jValue, value);
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -681,7 +774,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresent
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -721,7 +817,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresent
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -753,7 +852,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueByteArray
     env->ReleaseByteArrayElements(jValue, bytes, JNI_ABORT);
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -769,10 +871,16 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_addChild
 {
     LOGD("OcRepresentation_addChild");
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     OCRepresentation *child = JniOcRepresentation::getOCRepresentationPtr(env, jOcRepresentation);
-    if (!child) return;
+    if (!child)
+    {
+        return;
+    }
 
     rep->addChild(*child);
 }
@@ -787,7 +895,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_clearChildren
 {
     LOGD("OcRepresentation_clearChildren");
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     rep->clearChildren();
 }
@@ -802,7 +913,10 @@ JNIEXPORT jobjectArray JNICALL Java_org_iotivity_base_OcRepresentation_getChildr
 {
     LOGD("OcRepresentation_getChildrenArray");
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return nullptr;
+    if (!rep)
+    {
+        return nullptr;
+    }
 
     return JniUtils::convertRepresentationVectorToJavaArray(env, rep->getChildren());
 }
@@ -817,7 +931,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcRepresentation_getUri
 {
     LOGD("OcRepresentation_getUri");
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return nullptr;
+    if (!rep)
+    {
+        return nullptr;
+    }
 
     std::string uri(rep->getUri());
     return env->NewStringUTF(uri.c_str());
@@ -833,7 +950,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcRepresentation_getHost
 {
     LOGD("OcRepresentation_getHost");
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return nullptr;
+    if (!rep)
+    {
+        return nullptr;
+    }
 
     std::string uri(rep->getHost());
     return env->NewStringUTF(uri.c_str());
@@ -854,7 +974,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setUri
         return;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     rep->setUri(env->GetStringUTFChars(jUri, nullptr));
 }
@@ -869,7 +992,10 @@ JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_hasAttribute
         return false;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return false;
+    if (!rep)
+    {
+        return false;
+    }
 
     std::string str = env->GetStringUTFChars(jstr, nullptr);
     return rep->hasAttribute(str);
@@ -885,7 +1011,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getResourceTyp
 {
     LOGD("OcRepresentation_getResourceTypes");
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return nullptr;
+    if (!rep)
+    {
+        return nullptr;
+    }
 
     std::vector<std::string> resourceTypes = rep->getResourceTypes();
     return JniUtils::convertStrVectorToJavaStrList(env, resourceTypes);
@@ -906,7 +1035,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setResourceTypeAr
         return;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::vector<std::string> resourceTypes;
     JniUtils::convertJavaStrArrToStrVector(env, jResourceTypeArray, resourceTypes);
@@ -922,7 +1054,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getResourceInt
 {
     LOGD("OcRepresentation_getResourceInterfaces");
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return nullptr;
+    if (!rep)
+    {
+        return nullptr;
+    }
 
     std::vector<std::string> resourceInterfaces = rep->getResourceInterfaces();
     return JniUtils::convertStrVectorToJavaStrList(env, resourceInterfaces);
@@ -943,7 +1078,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setResourceInterf
         return;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::vector<std::string> resourceInterfaces;
     JniUtils::convertJavaStrArrToStrVector(env, jResourceInterfaceArray, resourceInterfaces);
@@ -960,7 +1098,10 @@ JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_isEmpty
 {
     LOGD("OcRepresentation_isEmpty");
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return false;
+    if (!rep)
+    {
+        return false;
+    }
 
     return static_cast<jboolean>(rep->empty());
 }
@@ -975,7 +1116,10 @@ JNIEXPORT jint JNICALL Java_org_iotivity_base_OcRepresentation_size
 {
     LOGD("OcRepresentation_size");
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return -1;
+    if (!rep)
+    {
+        return -1;
+    }
 
     return static_cast<jint>(rep->numberOfAttributes());
 }
@@ -995,7 +1139,10 @@ JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_remove
         return false;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return false;
+    if (!rep)
+    {
+        return false;
+    }
 
     std::string attributeKey = env->GetStringUTFChars(jAttributeKey, nullptr);
     return static_cast<jboolean>(rep->erase(attributeKey));
@@ -1016,7 +1163,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setNull
         return;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string attributeKey = env->GetStringUTFChars(jAttributeKey, nullptr);
     rep->setNULL(attributeKey);
@@ -1037,7 +1187,10 @@ JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_isNull
         return false;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return false;
+    if (!rep)
+    {
+        return false;
+    }
 
     std::string attributeKey = env->GetStringUTFChars(jAttributeKey, nullptr);
     return static_cast<jboolean>(rep->isNULL(attributeKey));
index e0a87b6..e9acd35 100644 (file)
@@ -35,9 +35,15 @@ public:
 
 struct JObjectConverter : boost::static_visitor < jobject >
 {
-    JObjectConverter(JNIEnv *env) : env(env){}
+    JObjectConverter(JNIEnv *env) : env(env)
+    {
+    }
+
+    jobject operator()(const NullType&) const
+    {
+        return nullptr;
+    }
 
-    jobject operator()(const NullType&) const { return nullptr; }
     jobject operator()(const int& val) const
     {
         jobject jobj = env->NewObject(
@@ -87,7 +93,10 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         size_t len = val.size();
         jintArray jIntArray = env->NewIntArray(len);
-        if (!jIntArray) return nullptr;
+        if (!jIntArray)
+        {
+            return nullptr;
+        }
         const int* ints = &val[0];
         env->SetIntArrayRegion(jIntArray, 0, len, reinterpret_cast<const jint*>(ints));
         return jIntArray;
@@ -96,7 +105,10 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         size_t len = val.size();
         jdoubleArray jDoubleArray = env->NewDoubleArray(len);
-        if (!jDoubleArray) return nullptr;
+        if (!jDoubleArray)
+        {
+            return nullptr;
+        }
         const double* doubles = &val[0];
         env->SetDoubleArrayRegion(jDoubleArray, 0, len, reinterpret_cast<const jdouble*>(doubles));
         return jDoubleArray;
@@ -105,13 +117,20 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         size_t len = val.size();
         jbooleanArray jBooleanArray = env->NewBooleanArray(len);
-        if (!jBooleanArray) return nullptr;
+        if (!jBooleanArray)
+        {
+            return nullptr;
+        }
         jboolean* booleans = new jboolean[len];
-        for (size_t i = 0; i < len; ++i) {
+        for (size_t i = 0; i < len; ++i)
+        {
             booleans[i] = static_cast<jboolean>(val[i]);
         }
         env->SetBooleanArrayRegion(jBooleanArray, 0, len, booleans);
-        if (env->ExceptionCheck()) return nullptr;
+        if (env->ExceptionCheck())
+        {
+            return nullptr;
+        }
         env->ReleaseBooleanArrayElements(jBooleanArray, booleans, 0);
         return jBooleanArray;
     }
@@ -119,12 +138,18 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         size_t len = val.size();
         jobjectArray strArr = env->NewObjectArray(len, g_cls_String, nullptr);
-        if (!strArr) return nullptr;
+        if (!strArr)
+        {
+            return nullptr;
+        }
         for (size_t i = 0; i < len; ++i)
         {
             jstring jString = env->NewStringUTF(val[i].c_str());
             env->SetObjectArrayElement(strArr, static_cast<jsize>(i), jString);
-            if (env->ExceptionCheck()) return nullptr;
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }
             env->DeleteLocalRef(jString);
         }
         return strArr;
@@ -133,7 +158,10 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         jsize len = static_cast<jsize>(val.size());
         jobjectArray repArr = env->NewObjectArray(len, g_cls_OcRepresentation, nullptr);
-        if (!repArr) return nullptr;
+        if (!repArr)
+        {
+            return nullptr;
+        }
         for (jsize i = 0; i < len; ++i)
         {
             OCRepresentation* rep = new OCRepresentation(val[i]);
@@ -159,7 +187,10 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         size_t len = val.size();
         jbyteArray jByteArray = env->NewByteArray(len);
-        if (!jByteArray) return nullptr;
+        if (!jByteArray)
+        {
+            return nullptr;
+        }
         const uint8_t* bytes = &val[0];
         env->SetByteArrayRegion(jByteArray, 0, len, reinterpret_cast<const jbyte*>(bytes));
         return jByteArray;
@@ -178,12 +209,21 @@ struct JObjectConverter : boost::static_visitor < jobject >
         {
             size_t lenInner = val[i].size();
             jintArray jIntArray = env->NewIntArray(lenInner);
-            if (!jIntArray) return nullptr;
+            if (!jIntArray)
+            {
+                return nullptr;
+            }
             const int* ints = &val[i][0];
             env->SetIntArrayRegion(jIntArray, 0, lenInner, reinterpret_cast<const jint*>(ints));
-            if (env->ExceptionCheck()) return nullptr;
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }
             env->SetObjectArrayElement(jOuterArr, i, static_cast<jobject>(jIntArray));
-            if (env->ExceptionCheck()) return nullptr;
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }
             env->DeleteLocalRef(jIntArray);
         }
         return jOuterArr;
@@ -192,26 +232,46 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         jsize lenOuter = static_cast<jsize>(val.size());
         jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_int2DArray, nullptr);
-        if (!jOuterArr) return nullptr;
+        if (!jOuterArr)
+        {
+            return nullptr;
+        }
+
         for (jsize k = 0; k < lenOuter; ++k)
         {
             jsize lenMiddle = static_cast<jsize>(val[k].size());
             jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_int1DArray, nullptr);
-            if (!jMiddleArr) return nullptr;
+            if (!jMiddleArr)
+            {
+                return nullptr;
+            }
+
             for (jsize i = 0; i < lenMiddle; ++i)
             {
                 jsize lenInner = static_cast<jsize>(val[k][i].size());
                 jintArray jIntArray = env->NewIntArray(lenInner);
-                if (!jIntArray) return nullptr;
+                if (!jIntArray)
+                {
+                    return nullptr;
+                }
                 const int* ints = &val[k][i][0];
                 env->SetIntArrayRegion(jIntArray, 0, lenInner, reinterpret_cast<const jint*>(ints));
-                if (env->ExceptionCheck()) return nullptr;
+                if (env->ExceptionCheck())
+                {
+                    return nullptr;
+                }
                 env->SetObjectArrayElement(jMiddleArr, i, jIntArray);
-                if (env->ExceptionCheck()) return nullptr;
+                if (env->ExceptionCheck())
+                {
+                    return nullptr;
+                }
                 env->DeleteLocalRef(jIntArray);
             }
             env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
-            if (env->ExceptionCheck()) return nullptr;
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }
             env->DeleteLocalRef(jMiddleArr);
         }
         return jOuterArr;
@@ -221,17 +281,31 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         jsize lenOuter = static_cast<jsize>(val.size());
         jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_double1DArray, nullptr);
-        if (!jOuterArr) return nullptr;
+        if (!jOuterArr)
+        {
+            return nullptr;
+        }
+
         for (jsize i = 0; i < lenOuter; ++i)
         {
             size_t lenInner = val[i].size();
             jdoubleArray jDoubleArray = env->NewDoubleArray(lenInner);
-            if (!jDoubleArray) return nullptr;
+            if (!jDoubleArray)
+            {
+                return nullptr;
+            }
+
             const double* doubles = &val[i][0];
             env->SetDoubleArrayRegion(jDoubleArray, 0, lenInner, reinterpret_cast<const jdouble*>(doubles));
-            if (env->ExceptionCheck()) return nullptr;
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }
             env->SetObjectArrayElement(jOuterArr, i, jDoubleArray);
-            if (env->ExceptionCheck()) return nullptr;
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }
             env->DeleteLocalRef(jDoubleArray);
         }
 
@@ -241,26 +315,44 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         jsize lenOuter = static_cast<jsize>(val.size());
         jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_double2DArray, nullptr);
-        if (!jOuterArr) return nullptr;
+        if (!jOuterArr)
+        {
+            return nullptr;
+        }
         for (jsize k = 0; k < lenOuter; ++k)
         {
             jsize lenMiddle = static_cast<jsize>(val[k].size());
             jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_double1DArray, nullptr);
-            if (!jMiddleArr) return nullptr;
+            if (!jMiddleArr)
+            {
+                return nullptr;
+            }
             for (jsize i = 0; i < lenMiddle; ++i)
             {
                 jsize lenInner = static_cast<jsize>(val[k][i].size());
                 jdoubleArray jDoubleArray = env->NewDoubleArray(lenInner);
-                if (!jDoubleArray) return nullptr;
+                if (!jDoubleArray)
+                {
+                    return nullptr;
+                }
                 const double* doubles = &val[k][i][0];
                 env->SetDoubleArrayRegion(jDoubleArray, 0, lenInner, reinterpret_cast<const jdouble*>(doubles));
-                if (env->ExceptionCheck()) return nullptr;
+                if (env->ExceptionCheck())
+                {
+                    return nullptr;
+                }
                 env->SetObjectArrayElement(jMiddleArr, i, jDoubleArray);
-                if (env->ExceptionCheck()) return nullptr;
+                if (env->ExceptionCheck())
+                {
+                    return nullptr;
+                }
                 env->DeleteLocalRef(jDoubleArray);
             }
             env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
-            if (env->ExceptionCheck()) return nullptr;
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }
             env->DeleteLocalRef(jMiddleArr);
         }
         return jOuterArr;
@@ -270,22 +362,38 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         jsize lenOuter = static_cast<jsize>(val.size());
         jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_boolean1DArray, 0);
-        if (!jOuterArr) return nullptr;
+        if (!jOuterArr)
+        {
+            return nullptr;
+        }
         for (jsize i = 0; i < lenOuter; ++i)
         {
             size_t lenInner = val[i].size();
             jbooleanArray jBooleanArray = env->NewBooleanArray(lenInner);
-            if (!jBooleanArray) return nullptr;
+            if (!jBooleanArray)
+            {
+                return nullptr;
+            }
             jboolean* booleans = new jboolean[lenInner];
-            for (size_t j = 0; j < lenInner; ++j) {
+            for (size_t j = 0; j < lenInner; ++j)
+            {
                 booleans[j] = static_cast<jboolean>(val[i][j]);
             }
             env->SetBooleanArrayRegion(jBooleanArray, 0, lenInner, booleans);
-            if (env->ExceptionCheck()) return nullptr;
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }
             env->SetObjectArrayElement(jOuterArr, i, jBooleanArray);
-            if (env->ExceptionCheck()) return nullptr;
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }
             env->ReleaseBooleanArrayElements(jBooleanArray, booleans, 0);
-            if (env->ExceptionCheck()) return nullptr;
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }
             env->DeleteLocalRef(jBooleanArray);
         }
         return jOuterArr;
@@ -294,31 +402,49 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         jsize lenOuter = static_cast<jsize>(val.size());
         jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_boolean2DArray, nullptr);
-        if (!jOuterArr) return nullptr;
+        if (!jOuterArr)
+        {
+            return nullptr;
+        }
         for (jsize k = 0; k < lenOuter; ++k)
         {
             jsize lenMiddle = static_cast<jsize>(val[k].size());
             jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_boolean1DArray, nullptr);
-            if (!jMiddleArr) return nullptr;
+            if (!jMiddleArr)
+            {
+                return nullptr;
+            }
             for (jsize i = 0; i < lenMiddle; ++i)
             {
                 size_t lenInner = val[k][i].size();
                 jbooleanArray jBooleanArray = env->NewBooleanArray(lenInner);
                 jboolean* booleans = new jboolean[lenInner];
-                for (size_t j = 0; j < lenInner; ++j) {
+                for (size_t j = 0; j < lenInner; ++j)
+                {
                     booleans[j] = val[k][i][j];
                 }
                 env->SetBooleanArrayRegion(jBooleanArray, 0, lenInner, booleans);
-                if (env->ExceptionCheck()) return nullptr;
+                if (env->ExceptionCheck())
+                {
+                    return nullptr;
+                }
                 env->SetObjectArrayElement(jMiddleArr, i, jBooleanArray);
-                if (env->ExceptionCheck()) return nullptr;
+                if (env->ExceptionCheck())
+                {
+                    return nullptr;
+                }
                 env->ReleaseBooleanArrayElements(jBooleanArray, booleans, 0);
-                if (env->ExceptionCheck()) return nullptr;
+                if (env->ExceptionCheck())
+                {
+                    return nullptr;
+                }
                 env->DeleteLocalRef(jBooleanArray);
             }
             env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
-            if (env->ExceptionCheck()) return nullptr;
-            env->DeleteLocalRef(jMiddleArr);
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }            env->DeleteLocalRef(jMiddleArr);
         }
         return jOuterArr;
     }
@@ -327,21 +453,33 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         jsize lenOuter = static_cast<jsize>(val.size());
         jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_String1DArray, nullptr);
-        if (!jOuterArr) return nullptr;
+        if (!jOuterArr)
+        {
+            return nullptr;
+        }
         for (jsize i = 0; i < lenOuter; ++i)
         {
             jsize lenInner = static_cast<jsize>(val[i].size());
             jobjectArray strArr = env->NewObjectArray(lenInner, g_cls_String, nullptr);
-            if (!strArr) return nullptr;
+            if (!strArr)
+            {
+                return nullptr;
+            }
             for (jsize j = 0; j < lenInner; ++j)
             {
                 jstring jString = env->NewStringUTF(val[i][j].c_str());
                 env->SetObjectArrayElement(strArr, j, jString);
-                if (env->ExceptionCheck()) return nullptr;
+                if (env->ExceptionCheck())
+                {
+                    return nullptr;
+                }
                 env->DeleteLocalRef(jString);
             }
             env->SetObjectArrayElement(jOuterArr, i, strArr);
-            if (env->ExceptionCheck()) return nullptr;
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }
             env->DeleteLocalRef(strArr);
         }
 
@@ -351,30 +489,48 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         jsize lenOuter = static_cast<jsize>(val.size());
         jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_String2DArray, nullptr);
-        if (!jOuterArr) return nullptr;
+        if (!jOuterArr)
+        {
+            return nullptr;
+        }
         for (jsize k = 0; k < lenOuter; ++k)
         {
             jsize lenMiddle = static_cast<jsize>(val[k].size());
             jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_String1DArray, nullptr);
-            if (!jMiddleArr) return nullptr;
+            if (!jMiddleArr)
+            {
+                return nullptr;
+            }
             for (jsize i = 0; i < lenMiddle; ++i)
             {
                 jsize lenInner = static_cast<jsize>(val[k][i].size());
                 jobjectArray strArr = env->NewObjectArray(lenInner, g_cls_String, nullptr);
-                if (!strArr) return nullptr;
+                if (!strArr)
+                {
+                    return nullptr;
+                }
                 for (jsize j = 0; j < lenInner; ++j)
                 {
                     jstring jString = env->NewStringUTF(val[k][i][j].c_str());
                     env->SetObjectArrayElement(strArr, j, jString);
-                    if (env->ExceptionCheck()) return nullptr;
+                    if (env->ExceptionCheck())
+                    {
+                        return nullptr;
+                    }
                     env->DeleteLocalRef(jString);
                 }
                 env->SetObjectArrayElement(jMiddleArr, i, strArr);
-                if (env->ExceptionCheck()) return nullptr;
+                if (env->ExceptionCheck())
+                {
+                    return nullptr;
+                }
                 env->DeleteLocalRef(strArr);
             }
             env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
-            if (env->ExceptionCheck()) return nullptr;
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }
             env->DeleteLocalRef(jMiddleArr);
         }
         return jOuterArr;
@@ -384,12 +540,18 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         jsize lenOuter = static_cast<jsize>(val.size());
         jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_OcRepresentation1DArray, nullptr);
-        if (!jOuterArr) return nullptr;
+        if (!jOuterArr)
+        {
+            return nullptr;
+        }
         for (jsize i = 0; i < lenOuter; ++i)
         {
             jsize lenInner = static_cast<jsize>(val[i].size());
             jobjectArray repArr = env->NewObjectArray(lenInner, g_cls_OcRepresentation, nullptr);
-            if (!repArr) return nullptr;
+            if (!repArr)
+            {
+                return nullptr;
+            }
             for (jsize j = 0; j < lenInner; ++j)
             {
                 OCRepresentation* rep = new OCRepresentation(val[i][j]);
@@ -402,11 +564,17 @@ struct JObjectConverter : boost::static_visitor < jobject >
                     return nullptr;
                 }
                 env->SetObjectArrayElement(repArr, j, jRepresentation);
-                if (env->ExceptionCheck()) return nullptr;
+                if (env->ExceptionCheck())
+                {
+                    return nullptr;
+                }
                 env->DeleteLocalRef(jRepresentation);
             }
             env->SetObjectArrayElement(jOuterArr, i, repArr);
-            if (env->ExceptionCheck()) return nullptr;
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }
             env->DeleteLocalRef(repArr);
         }
         return jOuterArr;
@@ -415,17 +583,26 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         jsize lenOuter = static_cast<jsize>(val.size());
         jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_OcRepresentation2DArray, nullptr);
-        if (!jOuterArr) return nullptr;
+        if (!jOuterArr)
+        {
+            return nullptr;
+        }
         for (jsize k = 0; k < lenOuter; ++k)
         {
             jsize lenMiddle = static_cast<jsize>(val[k].size());
             jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_OcRepresentation1DArray, nullptr);
-            if (!jMiddleArr) return nullptr;
+            if (!jMiddleArr)
+            {
+                return nullptr;
+            }
             for (jsize i = 0; i < lenMiddle; ++i)
             {
                 jsize lenInner = static_cast<jsize>(val[k][i].size());
                 jobjectArray repArr = env->NewObjectArray(lenInner, g_cls_OcRepresentation, nullptr);
-                if (!repArr) return nullptr;
+                if (!repArr)
+                {
+                    return nullptr;
+                }
                 for (jsize j = 0; j < lenInner; ++j)
                 {
                     OCRepresentation* rep = new OCRepresentation(val[k][i][j]);
@@ -438,15 +615,24 @@ struct JObjectConverter : boost::static_visitor < jobject >
                         return nullptr;
                     }
                     env->SetObjectArrayElement(repArr, j, jRepresentation);
-                    if (env->ExceptionCheck()) return nullptr;
+                    if (env->ExceptionCheck())
+                    {
+                        return nullptr;
+                    }
                     env->DeleteLocalRef(jRepresentation);
                 }
                 env->SetObjectArrayElement(jMiddleArr, i, repArr);
-                if (env->ExceptionCheck()) return nullptr;
+                if (env->ExceptionCheck())
+                {
+                    return nullptr;
+                }
                 env->DeleteLocalRef(repArr);
             }
             env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
-            if (env->ExceptionCheck()) return nullptr;
+            if (env->ExceptionCheck())
+            {
+                return nullptr;
+            }
             env->DeleteLocalRef(jMiddleArr);
         }
         return jOuterArr;
@@ -462,6 +648,14 @@ extern "C" {
 
     /*
     * Class:     org_iotivity_base_OcRepresentation
+    * Method:    getValues
+    * Signature: ()Ljava/util/Map;
+    */
+    JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getValues
+        (JNIEnv *, jobject);
+
+    /*
+    * Class:     org_iotivity_base_OcRepresentation
     * Method:    getValueN
     * Signature: (Ljava/lang/String;)Ljava/lang/Object;
     */
index b916490..9585c55 100644 (file)
@@ -22,7 +22,8 @@
 #include "JniOcRequestHandle.h"
 
 JniOcRequestHandle::JniOcRequestHandle(OCRequestHandle requestHandle) : m_requestHandle(requestHandle)
-{}
+{
+}
 
 JniOcRequestHandle::~JniOcRequestHandle()
 {
@@ -60,4 +61,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRequestHandle_dispose
     LOGD("OcRequestHandle_dispose");
     JniOcRequestHandle *handle = JniOcRequestHandle::getJniOcRequestHandlePtr(env, thiz);
     delete handle;
-}
\ No newline at end of file
+}
index 9e6925a..743c1bc 100644 (file)
@@ -26,7 +26,8 @@
 
 JniOcResource::JniOcResource(std::shared_ptr<OCResource> resource)
     : m_sharedResource(resource)
-{}
+{
+}
 
 JniOcResource::~JniOcResource()
 {
@@ -34,9 +35,12 @@ JniOcResource::~JniOcResource()
 
     m_sharedResource = nullptr;
 
-    jint envRet;
+    jint envRet = JNI_ERR;
     JNIEnv *env = GetJNIEnv(envRet);
-    if (nullptr == env) return;
+    if (nullptr == env)
+    {
+        return;
+    }
 
     m_onGetManager.removeAllListeners(env);
     m_onPutManager.removeAllListeners(env);
@@ -44,7 +48,10 @@ JniOcResource::~JniOcResource()
     m_onDeleteManager.removeAllListeners(env);
     m_onObserveManager.removeAllListeners(env);
 
-    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == envRet)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 OCStackResult JniOcResource::get(JNIEnv* env, const QueryParamsMap &queryParametersMap, jobject jListener)
@@ -432,7 +439,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_get
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -476,7 +486,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_get1
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -533,7 +546,10 @@ jobject jQueryParamsMap, jobject jListener)
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -590,7 +606,10 @@ jobject jQueryParamsMap, jobject jListener, jint jQoS)
         resourceInterface = env->GetStringUTFChars(jResourceInterface, nullptr);
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -643,10 +662,16 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_put
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
-    if (!representation) return;
+    if (!representation)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -698,10 +723,16 @@ jobject jListener, jint jQoS)
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
-    if (!representation) return;
+    if (!representation)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -764,10 +795,16 @@ jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
-    if (!representation) return;
+    if (!representation)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -832,10 +869,16 @@ jobject jQueryParamsMap, jobject jListener, jint jQoS)
     }
 
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
-    if (!representation) return;
+    if (!representation)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -888,10 +931,16 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_post
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
-    if (!representation) return;
+    if (!representation)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -941,10 +990,16 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_post1
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
-    if (!representation) return;
+    if (!representation)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -1008,10 +1063,16 @@ jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)
     }
 
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
-    if (!representation) return;
+    if (!representation)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -1076,10 +1137,16 @@ jobject jRepresentation, jobject jQueryParamsMap, jobject jListener, jint jQoS)
     }
 
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
-    if (!representation) return;
+    if (!representation)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -1122,7 +1189,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_deleteResource
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     try
     {
@@ -1157,7 +1227,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_deleteResource1
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     try
     {
@@ -1199,7 +1272,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_observe
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -1246,7 +1322,10 @@ jobject jListener, jint jQoS)
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -1282,7 +1361,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_cancelObserve1
 {
     LOGD("OcResource_cancelObserve1");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     try
     {
@@ -1317,7 +1399,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_setHeaderOptions
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     HeaderOptions headerOptions;
     JniUtils::convertJavaHeaderOptionsArrToVector(env, jheaderOptionArr, headerOptions);
@@ -1335,7 +1420,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_unsetHeaderOptions
 {
     LOGD("OcResource_unsetHeaderOptions");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     resource->unsetHeaderOptions();
 }
@@ -1350,7 +1438,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResource_getHost
 {
     LOGD("OcResource_getHost");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return nullptr;
+    if (!resource)
+    {
+        return nullptr;
+    }
 
     return env->NewStringUTF(resource->host().c_str());
 }
@@ -1365,7 +1456,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResource_getUri
 {
     LOGD("OcResource_getUri");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return nullptr;
+    if (!resource)
+    {
+        return nullptr;
+    }
 
     return env->NewStringUTF(resource->uri().c_str());
 }
@@ -1380,7 +1474,10 @@ JNIEXPORT jint JNICALL Java_org_iotivity_base_OcResource_getConnectivityTypeN
 {
     LOGD("OcResource_getConnectivityType");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return -1;
+    if (!resource)
+    {
+        return -1;
+    }
 
     OCConnectivityType connectivityType = resource->connectivityType();
     return static_cast<jint>(connectivityType);
@@ -1396,6 +1493,11 @@ JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcResource_isObservable
 {
     LOGD("OcResource_isObservable");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
+    if (!resource)
+    {
+        return false;
+    }
+
     return (jboolean)resource->isObservable();
 }
 
@@ -1409,7 +1511,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResource_getResourceTypes
 {
     LOGD("OcResource_getResourceTypes");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return nullptr;
+    if (!resource)
+    {
+        return nullptr;
+    }
 
     std::vector<std::string> resourceTypes = resource->getResourceTypes();
 
@@ -1426,7 +1531,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResource_getResourceInterface
 {
     LOGD("OcResource_getResourceInterfaces");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return nullptr;
+    if (!resource)
+    {
+        return nullptr;
+    }
 
     std::vector<std::string> resourceInterfaces = resource->getResourceInterfaces();
 
@@ -1443,11 +1551,17 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResource_getUniqueIdentifier
 {
     LOGD("OcResource_getUniqueIdentifier");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return nullptr;
+    if (!resource)
+    {
+        return nullptr;
+    }
 
     JniOcResourceIdentifier *jniResourceIdentifier =
         new JniOcResourceIdentifier(resource->uniqueIdentifier());
-    if (!jniResourceIdentifier) return nullptr;
+    if (!jniResourceIdentifier)
+    {
+        return nullptr;
+    }
 
     jlong handle = reinterpret_cast<jlong>(jniResourceIdentifier);
     jobject jResourceIdentifier = env->NewObject(g_cls_OcResourceIdentifier,
@@ -1469,7 +1583,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResource_getServerId
 {
     LOGD("OcResource_getServerId");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return nullptr;
+    if (!resource)
+    {
+        return nullptr;
+    }
 
     return env->NewStringUTF(resource->sid().c_str());
 }
@@ -1485,4 +1602,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_dispose
     LOGD("OcResource_dispose");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
     delete resource;
-}
\ No newline at end of file
+}
index 2d438f2..92371f4 100644 (file)
@@ -25,7 +25,8 @@ using namespace OC;
 
 JniOcResourceHandle::JniOcResourceHandle(OCResourceHandle resourceHandle)
     : m_resourceHandle(resourceHandle)
-{}
+{
+}
 
 JniOcResourceHandle::~JniOcResourceHandle()
 {
@@ -63,4 +64,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceHandle_dispose
     LOGD("OcResourceHandle_dispose");
     JniOcResourceHandle *resourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env, thiz);
     delete resourceHandle;
-}
\ No newline at end of file
+}
index b0b7d65..beeb724 100644 (file)
@@ -24,7 +24,8 @@
 
 JniOcResourceIdentifier::JniOcResourceIdentifier(OC::OCResourceIdentifier resourceIdentifier)
     : m_resourceIdentifier(resourceIdentifier)
-{}
+{
+}
 
 JniOcResourceIdentifier::~JniOcResourceIdentifier()
 {
@@ -60,10 +61,16 @@ JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcResourceIdentifier_equalsN
 (JNIEnv *env, jobject jThiz, jobject jOther)
 {
     JniOcResourceIdentifier *thiz = JniOcResourceIdentifier::getJniOcResourceIdentifierPtr(env, jThiz);
-    if (!thiz) return false;
+    if (!thiz)
+    {
+        return false;
+    }
 
     JniOcResourceIdentifier *other = JniOcResourceIdentifier::getJniOcResourceIdentifierPtr(env, jOther);
-    if (!other) return false;
+    if (!other)
+    {
+        return false;
+    }
 
     if (thiz->getOCResourceIdentifier() == other->getOCResourceIdentifier())
     {
@@ -86,4 +93,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceIdentifier_dispose
     LOGD("JniOcResourceIdentifier_dispose");
     JniOcResourceIdentifier *identifier = JniOcResourceIdentifier::getJniOcResourceIdentifierPtr(env, thiz);
     delete identifier;
-}
\ No newline at end of file
+}
index c943f70..c977bac 100644 (file)
@@ -29,10 +29,12 @@ using namespace OC;
 
 JniOcResourceRequest::JniOcResourceRequest(const std::shared_ptr<OCResourceRequest> request)
     : m_request(request)
-{}
+{
+}
 
 JniOcResourceRequest::~JniOcResourceRequest()
-{}
+{
+}
 
 std::string
 JniOcResourceRequest::getRequestType()
@@ -119,8 +121,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResourceRequest_getRequestTyp
 {
     LOGD("OcResourceRequest_getRequestTypeNative");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return nullptr;
-
+    if (!request)
+    {
+        return nullptr;
+    }
     std::string requestType = request->getRequestType();
     return env->NewStringUTF(requestType.c_str());
 }
@@ -135,7 +139,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getQueryParam
 {
     LOGD("OcResourceRequest_getQueryParameters");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return nullptr;
+    if (!request)
+    {
+        return nullptr;
+    }
 
     return JniUtils::convertQueryParamsMapToJavaMap(env, request->getQueryParameters());
 }
@@ -150,7 +157,10 @@ JNIEXPORT jint JNICALL Java_org_iotivity_base_OcResourceRequest_getRequestHandle
 {
     LOGD("OcResourceRequest_getRequestHandlerFlagNative");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return -1;
+    if (!request)
+    {
+        return -1;
+    }
 
     return static_cast<jint>(request->getRequestHandlerFlag());
 }
@@ -165,10 +175,16 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getResourceRe
 {
     LOGD("OcResourceRequest_getResourceRepresentation");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return nullptr;
+    if (!request)
+    {
+        return nullptr;
+    }
 
     OCRepresentation *ocRepresentation = new OCRepresentation(request->getResourceRepresentation());
-    if (!ocRepresentation) return nullptr;
+    if (!ocRepresentation)
+    {
+        return nullptr;
+    }
 
     jlong handle = reinterpret_cast<jlong>(ocRepresentation);
     jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,
@@ -192,8 +208,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getObservatio
 {
     LOGD("OcResourceRequest_getObservationInfo");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return nullptr;
-
+    if (!request)
+    {
+        return nullptr;
+    }
     ObservationInfo oInfo = request->getObservationInfo();
 
     jobject jObservationInfo = env->NewObject(g_cls_ObservationInfo, g_mid_ObservationInfo_N_ctor,
@@ -222,8 +240,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceRequest_setResourceUri
         return;
     }
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return;
-
+    if (!request)
+    {
+        return;
+    }
     request->setResourceUri(env->GetStringUTFChars(jUri, 0));
 }
 
@@ -237,8 +257,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResourceRequest_getResourceUr
 {
     LOGD("OcResourceRequest_getResourceUri");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return nullptr;
-
+    if (!request)
+    {
+        return nullptr;
+    }
     std::string requestUri = request->getResourceUri();
     return env->NewStringUTF(requestUri.c_str());
 }
@@ -253,8 +275,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getHeaderOpti
 {
     LOGD("OcResourceRequest_getHeaderOptions");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return nullptr;
-
+    if (!request)
+    {
+        return nullptr;
+    }
     return JniUtils::convertHeaderOptionsVectorToJavaList(env, request->getHeaderOptions());
 }
 
@@ -268,7 +292,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getRequestHan
 {
     LOGD("OcResourceRequest_getRequestHandle");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return nullptr;
+    if (!request)
+    {
+        return nullptr;
+    }
 
     JniOcRequestHandle* jniHandle = new JniOcRequestHandle(request->getRequestHandle());
     jlong handle = reinterpret_cast<jlong>(jniHandle);
@@ -292,7 +319,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getResourceHa
 {
     LOGD("OcResourceRequest_getResourceHandle");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return nullptr;
+    if (!request)
+    {
+        return nullptr;
+    }
 
     JniOcResourceHandle* jniHandle = new JniOcResourceHandle(
         request->getResourceHandle());
@@ -318,4 +348,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceRequest_dispose
     LOGD("OcResourceRequest_dispose");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
     delete request;
-}
\ No newline at end of file
+}
index 0781d9f..8189073 100644 (file)
@@ -30,10 +30,13 @@ using namespace OC;
 
 JniOcResourceResponse::JniOcResourceResponse
 (std::shared_ptr<OCResourceResponse> resourceResponse)
-: m_response(resourceResponse){}
+: m_response(resourceResponse)
+{
+}
 
 JniOcResourceResponse::~JniOcResourceResponse()
-{}
+{
+}
 
 void JniOcResourceResponse::setErrorCode(const int eCode)
 {
@@ -111,8 +114,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setErrorCode
 {
     LOGD("OcResourceResponse_setErrorCode");
     JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
-    if (!response) return;
-
+    if (!response)
+    {
+        return;
+    }
     response->setErrorCode(static_cast<int>(eCode));
 }
 
@@ -126,8 +131,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResourceResponse_getNewResour
 {
     LOGD("OcResourceResponse_getNewResourceUri");
     JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
-    if (!response) return nullptr;
-
+    if (!response)
+    {
+        return nullptr;
+    }
     return env->NewStringUTF(response->getNewResourceUri().c_str());
 }
 
@@ -141,8 +148,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setNewResourceU
 {
     LOGD("OcResourceResponse_setNewResourceUri");
     JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
-    if (!response) return;
-
+    if (!response)
+    {
+        return;
+    }
     response->setNewResourceUri(env->GetStringUTFChars(jstr, 0));
 }
 
@@ -161,8 +170,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setHeaderOption
         return;
     }
     JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
-    if (!jniResponse) return;
-
+    if (!jniResponse)
+    {
+        return;
+    }
     HeaderOptions headerOptions;
     JniUtils::convertJavaHeaderOptionsArrToVector(env, jHeaderOptions, headerOptions);
 
@@ -184,11 +195,15 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setRequestHandl
         return;
     }
     JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
-    if (!jniResponse) return;
-
+    if (!jniResponse)
+    {
+        return;
+    }
     JniOcRequestHandle* jniOcRequestHandle = JniOcRequestHandle::getJniOcRequestHandlePtr(env, jRequestHandle);
-    if (!jniOcRequestHandle) return;
-
+    if (!jniOcRequestHandle)
+    {
+        return;
+    }
     jniResponse->setRequestHandle(jniOcRequestHandle->getOCRequestHandle());
 }
 
@@ -207,11 +222,15 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceHand
         return;
     }
     JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
-    if (!jniResponse) return;
-
+    if (!jniResponse)
+    {
+        return;
+    }
     JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceHandle);
-    if (!jniOcResourceHandle) return;
-
+    if (!jniOcResourceHandle)
+    {
+        return;
+    }
     jniResponse->setResourceHandle(jniOcResourceHandle->getOCResourceHandle());
 }
 
@@ -225,8 +244,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResponseResu
 {
     LOGD("OcResourceResponse_setResponseResult");
     JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
-    if (!response) return;
-
+    if (!response)
+    {
+        return;
+    }
     response->setResponseResult(JniUtils::getOCEntityHandlerResult(env, static_cast<int>(responseResult)));
 }
 
@@ -252,12 +273,16 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceRepr
 
     JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env,
         thiz);
-    if (!response) return;
-
+    if (!response)
+    {
+        return;
+    }
     OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env,
         jRepresentation);
-    if (!representation) return;
-
+    if (!representation)
+    {
+        return;
+    }
     response->setResourceRepresentation(*representation, env->GetStringUTFChars(jstr, 0));
 }
 
@@ -276,8 +301,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceRepr
         return;
     }
     JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
-    if (!response) return;
-
+    if (!response)
+    {
+        return;
+    }
     OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env,
         jRepresentation);
 
@@ -317,4 +344,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_dispose
     LOGD("OcResourceResponse_dispose");
     JniOcResourceResponse *resp = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
     delete resp;
-}
\ No newline at end of file
+}
index 77c8dc6..7585b7b 100644 (file)
 
 #include "JniOcSecureResource.h"
 #include "JniSecureUtils.h"
+#include "oic_string.h"
 namespace PH = std::placeholders;
 
 JniOcSecureResource::JniOcSecureResource(std::shared_ptr<OCSecureResource> device)
     : m_sharedSecureResource(device)
-{}
+{
+}
 
 JniOcSecureResource::~JniOcSecureResource()
 {
@@ -240,6 +242,89 @@ OCStackResult JniOcSecureResource::provisionACL(JNIEnv* env, jobject _acl, jobje
     return ret;
 }
 
+OCStackResult JniOcSecureResource::provisionDirectPairing(JNIEnv* env, jobjectArray jpdacls,
+        jobject jListener, std::string pin, std::vector<int> prms, int edp)
+{
+    OCStackResult ret;
+    JniProvisionResultListner *resultListener = AddProvisionResultListener(env, jListener);
+
+    jsize len = env->GetArrayLength(jpdacls);
+
+    OicSecPconf_t *pconf = nullptr;
+    OicSecPdAcl_t *head = nullptr;
+
+    for (jsize i = 0; i < len; ++i)
+    {
+        OicSecPdAcl_t *pdacl = new OicSecPdAcl_t;
+        if (!pdacl)
+        {
+            return OC_STACK_NO_MEMORY;
+        }
+
+        memset(pdacl, 0, sizeof(OicSecPdAcl_t));
+        pdacl->next = nullptr;
+
+        jobject jpdacl  = env->GetObjectArrayElement(jpdacls, i);
+
+        if (OC_STACK_OK != JniSecureUtils::convertJavaPdACLToOCAcl(env, jpdacl, pdacl))
+        {
+            delete pdacl;
+            return OC_STACK_ERROR;
+        }
+
+        pdacl->next = head;
+        head = pdacl;
+    }
+
+    pconf = new OicSecPconf_t;
+    memset(pconf, 0, sizeof(OicSecPconf_t));
+    pconf->edp = edp;
+    pconf->prmLen = prms.size();
+    pconf->prm = new OicSecPrm_t[pconf->prmLen];
+    pconf->pddevLen = 0;
+
+    for (int i = 0 ; i < prms.size(); i++)
+        pconf->prm[i] = (OicSecPrm_t)prms[i];
+
+    memcpy(pconf->pin.val, pin.c_str(), DP_PIN_LENGTH);
+    pconf->pdacls = head;
+
+    ResultCallBack resultCallback = [head, resultListener, pconf, prms]
+        (PMResultList_t *result, int hasError)
+        {
+            OicSecPdAcl_t *tmp1, *tmp2;
+            tmp1 = head;
+            while (tmp1)
+            {
+                tmp2 = tmp1->next;
+                delete tmp1;
+                tmp1 = tmp2;
+            }
+
+            delete pconf->prm;
+            delete pconf;
+            resultListener->ProvisionResultCallback(result, hasError, ListenerFunc::PROVISIONDIRECTPAIRING);
+        };
+
+    ret = m_sharedSecureResource->provisionDirectPairing(pconf, resultCallback);
+
+    if (ret != OC_STACK_OK)
+    {
+        OicSecPdAcl_t *tmp1, *tmp2;
+        tmp1 = head;
+        while (tmp1)
+        {
+            tmp2 = tmp1->next;
+            delete tmp1;
+            tmp1 = tmp2;
+        }
+
+        delete pconf->prm;
+        delete pconf;
+    }
+    return ret;
+}
+
 OCStackResult JniOcSecureResource::provisionPairwiseDevices(JNIEnv* env, jint type, jint keySize,
         jobject _acl1, jobject _device2, jobject _acl2, jobject jListener)
 {
@@ -543,6 +628,55 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionPairwise
 
 /*
  * Class:     org_iotivity_base_OcSecureResource
+ * Method:    provisionDirectPairing
+ * Signature: (Ljava/lang/String;[Lorg/iotivity/base/OicSecPdAcl;ILorg/iotivity/base/OcSecureResource/ProvisionDirectPairingListener;I)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionDirectPairing
+(JNIEnv *env, jobject thiz, jstring jpin, jobjectArray pdacls, jintArray jprmType,
+    jint jedp, jobject jListener)
+{
+    LOGD("OcSecureResource_provisionDirectPairing");
+    if (!jListener || !pdacls || !jpin || ! jprmType)
+    {
+        ThrowOcException(OC_STACK_INVALID_PARAM, "Invalid Parameters");
+        return;
+    }
+    std::string pin = env->GetStringUTFChars(jpin, nullptr);
+
+    JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
+    if (!secureResource)
+    {
+        return;
+    }
+
+    const jsize len = env->GetArrayLength(jprmType);
+    jint* ints = env->GetIntArrayElements(jprmType, nullptr);
+    std::vector<int> value;
+    for (jsize i = 0; i < len; ++i)
+    {
+        value.push_back(static_cast<int>(ints[i]));
+    }
+    env->ReleaseIntArrayElements(jprmType, ints, JNI_ABORT);
+
+    try
+    {
+        OCStackResult result = secureResource->provisionDirectPairing(env, pdacls, jListener,
+                pin, value, static_cast<int>(jedp));
+        if (OC_STACK_OK != result)
+        {
+            ThrowOcException(result, "OcSecureResource_provisionDirectPairing");
+            return;
+        }
+    }
+    catch (OCException& e)
+    {
+        LOGE("%s", e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
+    }
+}
+
+/*
+ * Class:     org_iotivity_base_OcSecureResource
  * Method:    getLinkedDevices
  * Signature: ()Ljava/util/List;
  */
index 0b98f75..d071e96 100644 (file)
@@ -55,7 +55,8 @@ class JniOcSecureResource
                 jobject device2, 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,
+                std::string pin, std::vector<int> prms, int edp);
     private:
 
         std::map<jobject, std::pair<JniProvisionResultListner*, int>> resultMap;
@@ -118,6 +119,14 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionPairwise
 
 /*
  * Class:     org_iotivity_base_OcSecureResource
+ * Method:    provisionDirectPairing
+ * Signature: (Ljava/lang/Object;Lorg/iotivity/base/OcSecureResource/ProvisionDirectPairingListener;)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionDirectPairing
+  (JNIEnv *, jobject, jstring, jobjectArray, jintArray, jint, jobject);
+
+/*
+ * Class:     org_iotivity_base_OcSecureResource
  * Method:    getLinkedDevices
  * Signature: ()Ljava/util/List;
  */
index c5c3d7d..e2c6175 100644 (file)
 #include "OCRepresentation.h"
 #include "JniUtils.h"
 
+/**
+ * Macro to verify the validity of input argument.
+ *
+ * @param  arg  log level
+ */
+#define VERIFY_VARIABLE_NULL(arg) \
+    if (nullptr == (arg)) \
+    { \
+        LOGE("invalid input"); \
+        return JNI_ERR; \
+    } \
+
 JavaVM* g_jvm = nullptr;
 
 jclass g_cls_Integer = nullptr;
@@ -62,6 +74,8 @@ jclass g_cls_OcResourceIdentifier = nullptr;
 jclass g_cls_OcProvisionResult = nullptr;
 jclass g_cls_OcSecureResource = nullptr;
 jclass g_cls_OcOicSecAcl = nullptr;
+jclass g_cls_OcOicSecPdAcl = nullptr;
+jclass g_cls_OcDirectPairDevice = nullptr;
 
 jmethodID g_mid_Integer_ctor = nullptr;
 jmethodID g_mid_Double_ctor = nullptr;
@@ -94,6 +108,8 @@ jmethodID g_mid_OcPresenceStatus_get = nullptr;
 jmethodID g_mid_OcResourceIdentifier_N_ctor = nullptr;
 jmethodID g_mid_OcProvisionResult_ctor = nullptr;
 jmethodID g_mid_OcSecureResource_ctor = nullptr;
+jmethodID g_mid_OcDirectPairDevice_ctor = nullptr;
+jmethodID g_mid_OcDirectPairDevice_dev_ctor = nullptr;
 
 jmethodID g_mid_OcOicSecAcl_get_subject = nullptr;
 jmethodID g_mid_OcOicSecAcl_get_resources_cnt = nullptr;
@@ -103,6 +119,12 @@ jmethodID g_mid_OcOicSecAcl_get_periods_cnt = nullptr;
 jmethodID g_mid_OcOicSecAcl_get_periods = nullptr;
 jmethodID g_mid_OcOicSecAcl_get_recurrences = nullptr;
 jmethodID g_mid_OcOicSecAcl_get_rownerID = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_resources_cnt = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_resources = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_permission = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_periods_cnt = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_periods = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_recurrences = nullptr;
 
 jobject getOcException(JNIEnv* env, const char* file, const char* functionName,
     const int line, const int code, const char* message)
@@ -141,7 +163,7 @@ void throwOcException(JNIEnv* env, jobject ex)
 JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
 {
     LOGI("JNI_OnLoad");
-    JNIEnv* env;
+    JNIEnv* env = nullptr;
     g_jvm = vm;
 
     if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
@@ -149,316 +171,353 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
         LOGE("Failed to get the environment using GetEnv()");
         return JNI_ERR;
     }
+    VERIFY_VARIABLE_NULL(env);
 
     jclass clazz = nullptr;
 
     //Integer
     clazz = env->FindClass("java/lang/Integer");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
+
     g_cls_Integer = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_Integer_ctor = env->GetMethodID(g_cls_Integer, "<init>", "(I)V");
-    if (!g_mid_Integer_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_Integer_ctor);
 
     clazz = env->FindClass("[I");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_int1DArray = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     clazz = env->FindClass("[[I");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_int2DArray = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     //Double
     clazz = env->FindClass("java/lang/Double");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_Double = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_Double_ctor = env->GetMethodID(g_cls_Double, "<init>", "(D)V");
-    if (!g_mid_Double_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_Double_ctor);
 
     clazz = env->FindClass("[D");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_double1DArray = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     clazz = env->FindClass("[[D");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_double2DArray = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     //Boolean
     clazz = env->FindClass("java/lang/Boolean");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_Boolean = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_Boolean_ctor = env->GetMethodID(g_cls_Boolean, "<init>", "(Z)V");
-    if (!g_mid_Boolean_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_Boolean_ctor);
 
     clazz = env->FindClass("[Z");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_boolean1DArray = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     clazz = env->FindClass("[[Z");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_boolean2DArray = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     //String
     clazz = env->FindClass("java/lang/String");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_String = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     clazz = env->FindClass("[Ljava/lang/String;");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_String1DArray = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     clazz = env->FindClass("[[Ljava/lang/String;");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_String2DArray = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     //LinkedList
     clazz = env->FindClass("java/util/LinkedList");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_LinkedList = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_LinkedList_ctor = env->GetMethodID(g_cls_LinkedList, "<init>", "()V");
-    if (!g_mid_LinkedList_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_LinkedList_ctor);
 
     g_mid_LinkedList_add_object = env->GetMethodID(g_cls_LinkedList, "add", "(Ljava/lang/Object;)Z");
-    if (!g_mid_LinkedList_add_object) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_LinkedList_add_object);
 
     //Map
     clazz = env->FindClass("java/util/Map");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_Map = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_Map_entrySet = env->GetMethodID(g_cls_Map, "entrySet", "()Ljava/util/Set;");
-    if (!g_mid_Map_entrySet) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_Map_entrySet);
 
     //MapEntry
     clazz = env->FindClass("java/util/Map$Entry");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_MapEntry = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_MapEntry_getKey = env->GetMethodID(g_cls_MapEntry, "getKey", "()Ljava/lang/Object;");
-    if (!g_mid_MapEntry_getKey) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_MapEntry_getKey);
     g_mid_MapEntry_getValue = env->GetMethodID(g_cls_MapEntry, "getValue", "()Ljava/lang/Object;");
-    if (!g_mid_MapEntry_getValue) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_MapEntry_getValue);
 
     //Set
     clazz = env->FindClass("java/util/Set");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_Set = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_Set_iterator = env->GetMethodID(g_cls_Set, "iterator", "()Ljava/util/Iterator;");
-    if (!g_mid_Set_iterator) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_Set_iterator);
 
     //Iterator
     clazz = env->FindClass("java/util/Iterator");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_Iterator = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_Iterator_hasNext = env->GetMethodID(g_cls_Iterator, "hasNext", "()Z");
-    if (!g_mid_Iterator_hasNext) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_Iterator_hasNext);
 
     g_mid_Iterator_next = env->GetMethodID(g_cls_Iterator, "next", "()Ljava/lang/Object;");
-    if (!g_mid_Iterator_next) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_Iterator_next);
 
     //HashMap
     clazz = env->FindClass("java/util/HashMap");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_HashMap = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_HashMap_ctor = env->GetMethodID(g_cls_HashMap, "<init>", "()V");
-    if (!g_mid_HashMap_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_HashMap_ctor);
 
     g_mid_HashMap_put = env->GetMethodID(g_cls_HashMap, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
-    if (!g_mid_HashMap_put) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_HashMap_put);
 
     //OcException
     clazz = env->FindClass("org/iotivity/base/OcException");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcException = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_OcException_ctor = env->GetMethodID(g_cls_OcException, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");
-    if (!g_mid_OcException_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcException_ctor);
 
     g_mid_OcException_setNativeExceptionLocation = env->GetMethodID(g_cls_OcException, "setNativeExceptionLocation",
         "(Ljava/lang/String;""Ljava/lang/String;""I)V");
-    if (!g_mid_OcException_setNativeExceptionLocation) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcException_setNativeExceptionLocation);
 
     //OcResource
     clazz = env->FindClass("org/iotivity/base/OcResource");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcResource = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_OcResource_ctor = env->GetMethodID(g_cls_OcResource, "<init>", "(J)V");
-    if (!g_mid_OcResource_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcResource_ctor);
 
     //OcRepresentation
     clazz = env->FindClass("org/iotivity/base/OcRepresentation");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcRepresentation = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_OcRepresentation_N_ctor = env->GetMethodID(g_cls_OcRepresentation, "<init>", "(J)V");
-    if (!g_mid_OcRepresentation_N_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcRepresentation_N_ctor);
 
     g_mid_OcRepresentation_N_ctor_bool = env->GetMethodID(g_cls_OcRepresentation, "<init>", "(JZ)V");
-    if (!g_mid_OcRepresentation_N_ctor_bool) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcRepresentation_N_ctor_bool);
 
     clazz = env->FindClass("[Lorg/iotivity/base/OcRepresentation;");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcRepresentation1DArray = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     clazz = env->FindClass("[[Lorg/iotivity/base/OcRepresentation;");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcRepresentation2DArray = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     //HeaderOptions
     clazz = env->FindClass("org/iotivity/base/OcHeaderOption");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcHeaderOption = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
     g_mid_OcHeaderOption_ctor = env->GetMethodID(g_cls_OcHeaderOption, "<init>", "(ILjava/lang/String;)V");
-    if (!g_mid_OcHeaderOption_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcHeaderOption_ctor);
 
     g_mid_OcHeaderOption_get_id = env->GetMethodID(g_cls_OcHeaderOption, "getOptionId", "()I");
-    if (!g_mid_OcHeaderOption_get_id) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcHeaderOption_get_id);
 
     g_mid_OcHeaderOption_get_data = env->GetMethodID(g_cls_OcHeaderOption, "getOptionData", "()Ljava/lang/String;");
-    if (!g_mid_OcHeaderOption_get_data) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcHeaderOption_get_data);
 
     //OcResourceRequest
     clazz = env->FindClass("org/iotivity/base/OcResourceRequest");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcResourceRequest = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_OcResourceRequest_N_ctor = env->GetMethodID(g_cls_OcResourceRequest, "<init>", "(J)V");
-    if (!g_mid_OcResourceRequest_N_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcResourceRequest_N_ctor);
 
     //OcResourceResponse
     clazz = env->FindClass("org/iotivity/base/OcResourceResponse");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcResourceResponse = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_OcResourceResponse_N_ctor = env->GetMethodID(g_cls_OcResourceResponse, "<init>", "(J)V");
-    if (!g_mid_OcResourceResponse_N_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcResourceResponse_N_ctor);
 
     //OcResourceHandle
     clazz = env->FindClass("org/iotivity/base/OcResourceHandle");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcResourceHandle = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
     g_mid_OcResourceHandle_N_ctor = env->GetMethodID(g_cls_OcResourceHandle, "<init>", "(J)V");
-    if (!g_mid_OcResourceHandle_N_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcResourceHandle_N_ctor);
 
     //OcPresenceHandle
     clazz = env->FindClass("org/iotivity/base/OcPresenceHandle");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcPresenceHandle = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
     g_mid_OcPresenceHandle_N_ctor = env->GetMethodID(g_cls_OcPresenceHandle, "<init>", "(J)V");
-    if (!g_mid_OcPresenceHandle_N_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcPresenceHandle_N_ctor);
 
     //OcRequestHandle
     clazz = env->FindClass("org/iotivity/base/OcRequestHandle");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcRequestHandle = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
     g_mid_OcRequestHandle_N_ctor = env->GetMethodID(g_cls_OcRequestHandle, "<init>", "(J)V");
-    if (!g_mid_OcRequestHandle_N_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcRequestHandle_N_ctor);
 
     //OcPresenceStatus
     clazz = env->FindClass("org/iotivity/base/OcPresenceStatus");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcPresenceStatus = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
     g_mid_OcPresenceStatus_get = env->GetStaticMethodID(g_cls_OcPresenceStatus, "get",
         "(Ljava/lang/String;)Lorg/iotivity/base/OcPresenceStatus;");
-    if (!g_mid_OcPresenceStatus_get) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcPresenceStatus_get);
 
     //ObservationInfo
     clazz = env->FindClass("org/iotivity/base/ObservationInfo");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_ObservationInfo = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
     g_mid_ObservationInfo_N_ctor = env->GetMethodID(g_cls_ObservationInfo, "<init>", "(IB)V");
-    if (!g_mid_ObservationInfo_N_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_ObservationInfo_N_ctor);
 
     clazz = env->FindClass("org/iotivity/base/OcResourceIdentifier");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcResourceIdentifier = (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
     g_mid_OcResourceIdentifier_N_ctor = env->GetMethodID(g_cls_OcResourceIdentifier, "<init>", "(J)V");
-    if (!g_mid_OcResourceIdentifier_N_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcResourceIdentifier_N_ctor);
 
     //OcSecureResource
     clazz = env->FindClass("org/iotivity/base/OcSecureResource");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcSecureResource =  (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
     g_mid_OcSecureResource_ctor = env->GetMethodID(g_cls_OcSecureResource, "<init>", "(J)V");
-    if (!g_mid_OcSecureResource_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcSecureResource_ctor);
 
     //ProvisionResult
     clazz = env->FindClass("org/iotivity/base/ProvisionResult");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcProvisionResult =  (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
     g_mid_OcProvisionResult_ctor = env->GetMethodID(g_cls_OcProvisionResult, "<init>", "(Ljava/lang/String;I)V");
-    if (!g_mid_OcProvisionResult_ctor) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcProvisionResult_ctor);
+
+    //OcDirectPairDevice
+    clazz = env->FindClass("org/iotivity/base/OcDirectPairDevice");
+    VERIFY_VARIABLE_NULL(clazz);
+    g_cls_OcDirectPairDevice =  (jclass)env->NewGlobalRef(clazz);
+    g_mid_OcDirectPairDevice_ctor = env->GetMethodID(g_cls_OcDirectPairDevice, "<init>", "(J)V");
+    VERIFY_VARIABLE_NULL(g_mid_OcDirectPairDevice_ctor);
+
+    g_mid_OcDirectPairDevice_dev_ctor = env->GetMethodID(g_cls_OcDirectPairDevice, "<init>", "(Ljava/lang/String;)V");
+    VERIFY_VARIABLE_NULL(g_mid_OcDirectPairDevice_dev_ctor);
+    env->DeleteLocalRef(clazz);
 
     //OicSecAcl
     clazz = env->FindClass("org/iotivity/base/OicSecAcl");
-    if (!clazz) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(clazz);
     g_cls_OcOicSecAcl =  (jclass)env->NewGlobalRef(clazz);
     env->DeleteLocalRef(clazz);
 
     g_mid_OcOicSecAcl_get_subject = env->GetMethodID(g_cls_OcOicSecAcl, "getSubject", "()Ljava/lang/String;");
-    if (!g_mid_OcOicSecAcl_get_subject) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_subject);
 
     g_mid_OcOicSecAcl_get_resources_cnt = env->GetMethodID(g_cls_OcOicSecAcl, "getResourcesCount", "()I");
-    if (!g_mid_OcOicSecAcl_get_resources_cnt) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_resources_cnt);
 
     g_mid_OcOicSecAcl_get_resources = env->GetMethodID(g_cls_OcOicSecAcl, "getResources", "(I)Ljava/lang/String;");
-    if (!g_mid_OcOicSecAcl_get_resources) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_resources);
 
     g_mid_OcOicSecAcl_get_permission = env->GetMethodID(g_cls_OcOicSecAcl, "getPermission", "()I");
-    if (!g_mid_OcOicSecAcl_get_permission) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_permission);
 
     g_mid_OcOicSecAcl_get_periods_cnt = env->GetMethodID(g_cls_OcOicSecAcl, "getPeriodsCount", "()I");
-    if (!g_mid_OcOicSecAcl_get_periods_cnt) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_periods_cnt);
 
     g_mid_OcOicSecAcl_get_periods = env->GetMethodID(g_cls_OcOicSecAcl, "getPeriods", "(I)Ljava/lang/String;");
-    if (!g_mid_OcOicSecAcl_get_periods) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_periods);
 
     g_mid_OcOicSecAcl_get_recurrences = env->GetMethodID(g_cls_OcOicSecAcl, "getRecurrences", "(I)Ljava/lang/String;");
-    if (!g_mid_OcOicSecAcl_get_recurrences) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_recurrences);
 
     g_mid_OcOicSecAcl_get_rownerID = env->GetMethodID(g_cls_OcOicSecAcl, "getRownerID", "()Ljava/lang/String;");
-    if (!g_mid_OcOicSecAcl_get_rownerID) return JNI_ERR;
+    VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_rownerID);
+
+    //OicSecPdAcl
+    clazz = env->FindClass("org/iotivity/base/OicSecPdAcl");
+    VERIFY_VARIABLE_NULL(clazz);
+    g_cls_OcOicSecPdAcl =  (jclass)env->NewGlobalRef(clazz);
+    env->DeleteLocalRef(clazz);
+
+    g_mid_OcOicSecPdAcl_get_resources_cnt = env->GetMethodID(g_cls_OcOicSecPdAcl, "getResourcesCount", "()I");
+    VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_resources_cnt);
+
+    g_mid_OcOicSecPdAcl_get_resources = env->GetMethodID(g_cls_OcOicSecPdAcl, "getResources", "(I)Ljava/lang/String;");
+    VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_resources);
+
+    g_mid_OcOicSecPdAcl_get_permission = env->GetMethodID(g_cls_OcOicSecPdAcl, "getPermission", "()I");
+    VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_permission);
+
+    g_mid_OcOicSecPdAcl_get_periods_cnt = env->GetMethodID(g_cls_OcOicSecPdAcl, "getPeriodsCount", "()I");
+    VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_periods_cnt);
+
+    g_mid_OcOicSecPdAcl_get_periods = env->GetMethodID(g_cls_OcOicSecPdAcl, "getPeriods", "(I)Ljava/lang/String;");
+    VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_periods);
+
+    g_mid_OcOicSecPdAcl_get_recurrences = env->GetMethodID(g_cls_OcOicSecPdAcl, "getRecurrences", "(I)Ljava/lang/String;");
+    VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_recurrences);
 
     return JNI_CURRENT_VERSION;
 }
@@ -474,6 +533,7 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
         return;
     }
 
+
     env->DeleteGlobalRef(g_cls_Integer);
     env->DeleteGlobalRef(g_cls_int1DArray);
     env->DeleteGlobalRef(g_cls_int2DArray);
@@ -509,4 +569,4 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
     env->DeleteGlobalRef(g_cls_OcSecureResource);
     env->DeleteGlobalRef(g_cls_OcProvisionResult);
     env->DeleteGlobalRef(g_cls_OcOicSecAcl);
-}
\ No newline at end of file
+}
index b9f2ccd..7f7e851 100644 (file)
@@ -82,6 +82,8 @@ extern jclass g_cls_OcResourceIdentifier;
 extern jclass g_cls_OcProvisionResult;
 extern jclass g_cls_OcSecureResource;
 extern jclass g_cls_OcOicSecAcl;
+extern jclass g_cls_OcOicSecPdAcl;
+extern jclass g_cls_OcDirectPairDevice;
 
 extern jmethodID g_mid_Integer_ctor;
 extern jmethodID g_mid_Double_ctor;
@@ -114,6 +116,8 @@ extern jmethodID g_mid_OcPresenceStatus_get;
 extern jmethodID g_mid_OcResourceIdentifier_N_ctor;
 extern jmethodID g_mid_OcProvisionResult_ctor;
 extern jmethodID g_mid_OcSecureResource_ctor;
+extern jmethodID g_mid_OcDirectPairDevice_ctor;
+extern jmethodID g_mid_OcDirectPairDevice_dev_ctor;
 extern jmethodID g_mid_OcOicSecAcl_get_subject;
 extern jmethodID g_mid_OcOicSecAcl_get_resources_cnt;
 extern jmethodID g_mid_OcOicSecAcl_get_resources;
@@ -122,6 +126,12 @@ extern jmethodID g_mid_OcOicSecAcl_get_periods_cnt;
 extern jmethodID g_mid_OcOicSecAcl_get_periods;
 extern jmethodID g_mid_OcOicSecAcl_get_recurrences;
 extern jmethodID g_mid_OcOicSecAcl_get_rownerID;
+extern jmethodID g_mid_OcOicSecPdAcl_get_resources_cnt;
+extern jmethodID g_mid_OcOicSecPdAcl_get_resources;
+extern jmethodID g_mid_OcOicSecPdAcl_get_permission;
+extern jmethodID g_mid_OcOicSecPdAcl_get_periods_cnt;
+extern jmethodID g_mid_OcOicSecPdAcl_get_periods;
+extern jmethodID g_mid_OcOicSecPdAcl_get_recurrences;
 
 typedef void(*RemoveListenerCallback)(JNIEnv* env, jobject jListener);
 
@@ -151,26 +161,29 @@ static JNIEnv* GetJNIEnv(jint& ret)
     JNIEnv *env = nullptr;
 
     ret = g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION);
-    switch (ret) {
-    case JNI_OK:
-        return env;
-    case JNI_EDETACHED:
-        if (g_jvm->AttachCurrentThread(&env, nullptr) < 0)
-        {
+    switch (ret)
+    {
+        case JNI_OK:
+            return env;
+        case JNI_EDETACHED:
+            if (g_jvm->AttachCurrentThread(&env, nullptr) < 0)
+            {
+                LOGE("Failed to get the environment");
+                return nullptr;
+            }
+            else
+            {
+                return env;
+            }
+
+        case JNI_EVERSION:
+            LOGE("JNI version not supported");
+            break;
+        default:
             LOGE("Failed to get the environment");
             return nullptr;
-        }
-        else
-        {
-            return env;
-        }
-
-    case JNI_EVERSION:
-        LOGE("JNI version not supported");
-    default:
-        LOGE("Failed to get the environment");
-        return nullptr;
     }
+    return nullptr;
 }
 
 static void DuplicateString(char ** targetString, std::string sourceString)
@@ -179,4 +192,4 @@ static void DuplicateString(char ** targetString, std::string sourceString)
     strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
 }
 
-#endif // _Included_org_iotivity_base_ocstack
\ No newline at end of file
+#endif // _Included_org_iotivity_base_ocstack
diff --git a/android/android_api/base/jni/JniOnDPDevicesFoundListener.cpp b/android/android_api/base/jni/JniOnDPDevicesFoundListener.cpp
new file mode 100644 (file)
index 0000000..13db923
--- /dev/null
@@ -0,0 +1,190 @@
+/*
+* //******************************************************************
+* //
+* // 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 "JniOnDPDevicesFoundListener.h"
+#include "JniOcDirectPairDevice.h"
+#include "OCApi.h"
+using namespace OC;
+
+JniOnDPDevicesFoundListener::JniOnDPDevicesFoundListener(JNIEnv *env, jobject jListener,
+    RemoveListenerCallback removeListenerCallback)
+{
+    m_jwListener = env->NewWeakGlobalRef(jListener);
+    m_removeListenerCallback = removeListenerCallback;
+}
+
+jobject JniOnDPDevicesFoundListener::convertdpDevVectorToJavaList(JNIEnv *env, PairedDevices DPdevList)
+{
+    jobject jResultList = env->NewObject(g_cls_LinkedList, g_mid_LinkedList_ctor);
+    if (!jResultList)
+    {
+        return nullptr;
+    }
+
+    for (size_t i = 0; i < DPdevList.size(); ++i)
+    {
+        JniOcDirectPairDevice *device = new JniOcDirectPairDevice(DPdevList.at(i));
+        if (!device)
+        {
+            return nullptr;
+        }
+
+        jstring jStr = env->NewStringUTF(((DPdevList.at(i))->getDeviceID()).c_str());
+        if (!jStr)
+        {
+            return nullptr;
+        }
+        jobject jresult = env->NewObject(g_cls_OcDirectPairDevice,
+                g_mid_OcDirectPairDevice_dev_ctor,jStr);
+        if (!jresult)
+        {
+            return nullptr;
+        }
+
+        SetHandle<JniOcDirectPairDevice>(env, jresult, device);
+
+        env->CallBooleanMethod(jResultList, g_mid_LinkedList_add_object, jresult);
+        if (env->ExceptionCheck())
+        {
+            return nullptr;
+        }
+        env->DeleteLocalRef(jresult);
+        env->DeleteLocalRef(jStr);
+    }
+    return jResultList;
+}
+
+JniOnDPDevicesFoundListener::~JniOnDPDevicesFoundListener()
+{
+    LOGI("~JniOnDPDevicesFoundListener()");
+    if (m_jwListener)
+    {
+        jint ret = JNI_ERR;
+        JNIEnv *env = GetJNIEnv(ret);
+        if (nullptr == env)
+        {
+            return;
+        }
+        env->DeleteWeakGlobalRef(m_jwListener);
+        m_jwListener = nullptr;
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
+    }
+}
+
+void JniOnDPDevicesFoundListener::directPairingDevicesCallback(PairedDevices paringDevicesList, DPFunc func)
+{
+    jint ret;
+    JNIEnv *env = GetJNIEnv(ret);
+    if (nullptr == env)
+    {
+        return;
+    }
+
+    jobject jListener = env->NewLocalRef(m_jwListener);
+    if (!jListener)
+    {
+        checkExAndRemoveListener(env);
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
+        return;
+    }
+
+    jclass clsL = env->GetObjectClass(jListener);
+
+    if (!clsL)
+    {
+        checkExAndRemoveListener(env);
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
+        return;
+    }
+
+    jobject jpairingDevicesList = convertdpDevVectorToJavaList(env, paringDevicesList);
+    std::string calledFunc;
+    switch (func)
+    {
+        case DPFunc::FIND_DIRECT_PAIRED_DEV_LIST:
+            {
+                calledFunc = "onFindDirectPairingListener";
+            }
+            break;
+        case DPFunc::GET_PAIRED_DEV_LIST:
+            {
+                calledFunc = "onGetDirectPairedListener";
+            }
+            break;
+        default:
+            {
+                checkExAndRemoveListener(env);
+                if (JNI_EDETACHED == ret)
+                {
+                    g_jvm->DetachCurrentThread();
+                }
+            }
+            return;
+    }
+
+    jmethodID midL = env->GetMethodID(clsL, calledFunc.c_str(), "(Ljava/util/List;)V");
+
+    if (!midL)
+    {
+        checkExAndRemoveListener(env);
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
+        return;
+    }
+
+    env->CallVoidMethod(jListener, midL, jpairingDevicesList);
+    if (env->ExceptionCheck())
+    {
+        LOGE("Java exception is thrown");
+    }
+
+    checkExAndRemoveListener(env);
+    if (JNI_EDETACHED == ret)
+    {
+        g_jvm->DetachCurrentThread();
+    }
+}
+
+void JniOnDPDevicesFoundListener::checkExAndRemoveListener(JNIEnv* env)
+{
+    if (env->ExceptionCheck())
+    {
+        jthrowable ex = env->ExceptionOccurred();
+        env->ExceptionClear();
+        m_removeListenerCallback(env, m_jwListener);
+        env->Throw((jthrowable)ex);
+    }
+    else
+    {
+        m_removeListenerCallback(env, m_jwListener);
+    }
+}
diff --git a/android/android_api/base/jni/JniOnDPDevicesFoundListener.h b/android/android_api/base/jni/JniOnDPDevicesFoundListener.h
new file mode 100644 (file)
index 0000000..88acb61
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+* //******************************************************************
+* //
+* // 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 <jni.h>
+#include "OCDirectPairing.h"
+#include "OCApi.h"
+#include "JniOcStack.h"
+
+#ifndef _Included_org_iotivity_base_OcPlatform_JniOnDPDevicesFoundListener
+#define _Included_org_iotivity_base_OcPlatform_JniOnDPDevicesFoundListener
+
+enum class DPFunc
+{
+    FIND_DIRECT_PAIRED_DEV_LIST = 1,
+    GET_PAIRED_DEV_LIST,
+};
+
+class JniOnDPDevicesFoundListener
+{
+public:
+    JniOnDPDevicesFoundListener(JNIEnv *env, jobject jListener,
+            RemoveListenerCallback removeListenerCallback);
+    ~JniOnDPDevicesFoundListener();
+
+   jobject convertdpDevVectorToJavaList(JNIEnv *env, OC::PairedDevices DPdevList);
+   void directPairingDevicesCallback(OC::PairedDevices paringDevicesList, DPFunc);
+
+private:
+    RemoveListenerCallback m_removeListenerCallback;
+    jweak m_jwListener;
+    void checkExAndRemoveListener(JNIEnv* env);
+};
+#endif
index 87ebd71..4f95a4c 100644 (file)
@@ -34,35 +34,49 @@ JniOnDeleteListener::~JniOnDeleteListener()
 {
     if (m_jwListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
-        if (nullptr == env) return;
-
+        if (nullptr == env)
+        {
+            return;
+        }
         env->DeleteWeakGlobalRef(m_jwListener);
         m_jwListener = nullptr;
 
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
 }
 
 void JniOnDeleteListener::onDeleteCallback(const HeaderOptions& headerOptions, const int eCode)
 {
-    jint envRet;
+    jint envRet = JNI_ERR;
     JNIEnv *env = GetJNIEnv(envRet);
-    if (nullptr == env) return;
+    if (nullptr == env)
+    {
+        return;
+    }
 
     jobject jListener = env->NewLocalRef(m_jwListener);
     if (!jListener)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == envRet)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
     jclass clsL = env->GetObjectClass(jListener);
     if (!clsL)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == envRet)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -72,14 +86,20 @@ void JniOnDeleteListener::onDeleteCallback(const HeaderOptions& headerOptions, c
         if (!ex)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
         jmethodID midL = env->GetMethodID(clsL, "onDeleteFailed", "(Ljava/lang/Throwable;)V");
         if (!midL)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
         env->CallVoidMethod(jListener, midL, ex);
@@ -90,7 +110,10 @@ void JniOnDeleteListener::onDeleteCallback(const HeaderOptions& headerOptions, c
         if (!jHeaderOptionList)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -98,14 +121,20 @@ void JniOnDeleteListener::onDeleteCallback(const HeaderOptions& headerOptions, c
         if (!midL)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
         env->CallVoidMethod(jListener, midL, jHeaderOptionList);
     }
 
     checkExAndRemoveListener(env);
-    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == envRet)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnDeleteListener::checkExAndRemoveListener(JNIEnv* env)
@@ -121,4 +150,4 @@ void JniOnDeleteListener::checkExAndRemoveListener(JNIEnv* env)
     {
         m_ownerResource->removeOnDeleteListener(env, m_jwListener);
     }
-}
\ No newline at end of file
+}
index 28d8e44..520cdfd 100644 (file)
@@ -34,29 +34,41 @@ JniOnDeviceInfoListener::~JniOnDeviceInfoListener()
     LOGI("~JniOnDeviceInfoListener");
     if (m_jwListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
-        if (nullptr == env) return;
+        if (nullptr == env)
+        {
+            return;
+        }
 
         env->DeleteWeakGlobalRef(m_jwListener);
         m_jwListener = nullptr;
 
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
 }
 
 void JniOnDeviceInfoListener::foundDeviceCallback(const OC::OCRepresentation& ocRepresentation)
 {
-    jint ret;
+    jint ret = JNI_ERR;
     JNIEnv *env = GetJNIEnv(ret);
-    if (nullptr == env) return;
+    if (nullptr == env)
+    {
+        return;
+    }
 
     jobject jListener = env->NewLocalRef(m_jwListener);
     if (!jListener)
     {
         LOGI("Java onDeviceInfoListener object is already destroyed, quiting");
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -68,7 +80,10 @@ void JniOnDeviceInfoListener::foundDeviceCallback(const OC::OCRepresentation& oc
     {
         delete rep;
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -77,7 +92,10 @@ void JniOnDeviceInfoListener::foundDeviceCallback(const OC::OCRepresentation& oc
     {
         delete rep;
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
     jmethodID midL = env->GetMethodID(clsL, "onDeviceFound", "(Lorg/iotivity/base/OcRepresentation;)V");
@@ -85,7 +103,10 @@ void JniOnDeviceInfoListener::foundDeviceCallback(const OC::OCRepresentation& oc
     {
         delete rep;
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -97,7 +118,10 @@ void JniOnDeviceInfoListener::foundDeviceCallback(const OC::OCRepresentation& oc
         checkExAndRemoveListener(env);
     }
 
-    if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == ret)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnDeviceInfoListener::checkExAndRemoveListener(JNIEnv* env)
@@ -113,4 +137,4 @@ void JniOnDeviceInfoListener::checkExAndRemoveListener(JNIEnv* env)
     {
         m_removeListenerCallback(env, m_jwListener);
     }
-}
\ No newline at end of file
+}
diff --git a/android/android_api/base/jni/JniOnDirectPairingListener.cpp b/android/android_api/base/jni/JniOnDirectPairingListener.cpp
new file mode 100644 (file)
index 0000000..085c2b9
--- /dev/null
@@ -0,0 +1,159 @@
+/*
+* //******************************************************************
+* //
+* // 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 "JniOnDirectPairingListener.h"
+#include "JniOcDirectPairDevice.h"
+#include "OCDirectPairing.h"
+#include "OCApi.h"
+using namespace OC;
+
+JniOnDirectPairingListener::JniOnDirectPairingListener(JNIEnv *env, jobject jListener,
+    RemoveListenerCallback removeListenerCallback)
+{
+    m_jwListener = env->NewWeakGlobalRef(jListener);
+    m_removeListenerCallback = removeListenerCallback;
+}
+
+
+JniOnDirectPairingListener::~JniOnDirectPairingListener()
+{
+    LOGI("~JniOnDirectPairingListener()");
+    if (m_jwListener)
+    {
+        jint ret = JNI_ERR;
+        JNIEnv *env = GetJNIEnv(ret);
+        if (nullptr == env)
+        {
+            return;
+        }
+        env->DeleteWeakGlobalRef(m_jwListener);
+        m_jwListener = nullptr;
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
+    }
+}
+
+void JniOnDirectPairingListener::doDirectPairingCB(std::shared_ptr<OC::OCDirectPairing> dpDev,
+                                                                    OCStackResult result)
+{
+    jint ret = JNI_ERR;
+    JNIEnv *env = GetJNIEnv(ret);
+    if (nullptr == env)
+    {
+        return;
+    }
+
+    jobject jListener = env->NewLocalRef(m_jwListener);
+    if (!jListener)
+    {
+        checkExAndRemoveListener(env);
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
+        return;
+    }
+
+    jclass clsL = env->GetObjectClass(jListener);
+    if (!clsL)
+    {
+        checkExAndRemoveListener(env);
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
+        return;
+    }
+
+    JniOcDirectPairDevice *device = new JniOcDirectPairDevice(dpDev);
+    if (!device)
+    {
+        return;
+    }
+
+    jstring jStr = env->NewStringUTF((dpDev->getDeviceID()).c_str());
+    if (!jStr)
+    {
+        checkExAndRemoveListener(env);
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
+        return;
+    }
+
+    jobject jresult = env->NewObject(g_cls_OcDirectPairDevice, g_mid_OcDirectPairDevice_ctor);
+    if (!jresult)
+    {
+        checkExAndRemoveListener(env);
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
+        return;
+    }
+
+    SetHandle<JniOcDirectPairDevice>(env, jresult, device);
+
+    jint jres = static_cast<jint>(result);
+
+    jmethodID midL = env->GetMethodID(clsL, "onDirectPairingListener", "(Ljava/lang/String;I)V");
+
+    if (!midL)
+    {
+        checkExAndRemoveListener(env);
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
+        return;
+    }
+
+    env->CallVoidMethod(jListener, midL, jStr, jres);
+    if (env->ExceptionCheck())
+    {
+        LOGE("Java exception is thrown");
+    }
+
+    checkExAndRemoveListener(env);
+
+    if (JNI_EDETACHED == ret)
+    {
+        g_jvm->DetachCurrentThread();
+    }
+}
+
+void JniOnDirectPairingListener::checkExAndRemoveListener(JNIEnv* env)
+{
+    if (env->ExceptionCheck())
+    {
+        jthrowable ex = env->ExceptionOccurred();
+        env->ExceptionClear();
+        m_removeListenerCallback(env, m_jwListener);
+        env->Throw((jthrowable)ex);
+    }
+    else
+    {
+        m_removeListenerCallback(env, m_jwListener);
+    }
+}
diff --git a/android/android_api/base/jni/JniOnDirectPairingListener.h b/android/android_api/base/jni/JniOnDirectPairingListener.h
new file mode 100644 (file)
index 0000000..8ec2b7e
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+* //******************************************************************
+* //
+* // 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 <jni.h>
+#include "OCDirectPairing.h"
+#include "JniOcStack.h"
+
+#ifndef _Included_org_iotivity_base_OcPlatform_JniOnDirectPairingListener
+#define _Included_org_iotivity_base_OcPlatform_JniOnDirectPairingListener
+
+class JniOnDirectPairingListener
+{
+public:
+    JniOnDirectPairingListener(JNIEnv *env, jobject jListener,
+            RemoveListenerCallback removeListenerCallback);
+    ~JniOnDirectPairingListener();
+
+   void doDirectPairingCB(std::shared_ptr<OC::OCDirectPairing>, OCStackResult);
+
+private:
+    RemoveListenerCallback m_removeListenerCallback;
+    jweak m_jwListener;
+    void checkExAndRemoveListener(JNIEnv* env);
+};
+#endif
index 2bc8624..1a46903 100644 (file)
@@ -35,29 +35,41 @@ JniOnGetListener::~JniOnGetListener()
     LOGD("~JniOnGetListener");
     if (m_jwListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
-        if (nullptr == env) return;
+        if (nullptr == env)
+        {
+            return;
+        }
 
         env->DeleteWeakGlobalRef(m_jwListener);
         m_jwListener = nullptr;
 
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
 }
 
 void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
     const OCRepresentation& ocRepresentation, const int eCode)
 {
-    jint envRet;
+    jint envRet = JNI_ERR;
     JNIEnv *env = GetJNIEnv(envRet);
-    if (nullptr == env) return;
+    if (nullptr == env)
+    {
+        return;
+    }
 
     jobject jListener = env->NewLocalRef(m_jwListener);
     if (!jListener)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == envRet)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
     jclass clsL = env->GetObjectClass(jListener);
@@ -65,7 +77,10 @@ void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
     if (!clsL)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == envRet)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -75,14 +90,20 @@ void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
         if (!ex)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
         jmethodID midL = env->GetMethodID(clsL, "onGetFailed", "(Ljava/lang/Throwable;)V");
         if (!midL)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
         env->CallVoidMethod(jListener, midL, ex);
@@ -93,7 +114,10 @@ void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
         if (!jHeaderOptionList)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -105,7 +129,10 @@ void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
         {
             delete rep;
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -115,7 +142,10 @@ void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
         {
             delete rep;
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
         env->CallVoidMethod(jListener, midL, jHeaderOptionList, jRepresentation);
@@ -127,7 +157,10 @@ void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
     }
 
     checkExAndRemoveListener(env);
-    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == envRet)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnGetListener::checkExAndRemoveListener(JNIEnv* env)
@@ -143,4 +176,4 @@ void JniOnGetListener::checkExAndRemoveListener(JNIEnv* env)
     {
         m_ownerResource->removeOnGetListener(env, m_jwListener);
     }
-}
\ No newline at end of file
+}
index 3ad1d11..03d92f0 100644 (file)
@@ -34,36 +34,51 @@ JniOnObserveListener::~JniOnObserveListener()
 {
     if (m_jwListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
-        if (nullptr == env) return;
+        if (nullptr == env)
+        {
+            return;
+        }
 
         env->DeleteWeakGlobalRef(m_jwListener);
         m_jwListener = nullptr;
 
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
 }
 
 void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,
     const OCRepresentation& ocRepresentation, const int& eCode, const int& sequenceNumber)
 {
-    jint envRet;
+    jint envRet = JNI_ERR;
     JNIEnv *env = GetJNIEnv(envRet);
-    if (nullptr == env) return;
+    if (nullptr == env)
+    {
+        return;
+    }
 
     jobject jListener = env->NewLocalRef(m_jwListener);
     if (!jListener)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == envRet)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
     jclass clsL = env->GetObjectClass(jListener);
     if (!clsL)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == envRet)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -73,14 +88,20 @@ void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,
         if (!ex)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
         jmethodID midL = env->GetMethodID(clsL, "onObserveFailed", "(Ljava/lang/Throwable;)V");
         if (!midL)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
         env->CallVoidMethod(jListener, midL, ex);
@@ -91,7 +112,10 @@ void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,
         if (!jHeaderOptionList)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -103,7 +127,10 @@ void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,
         {
             delete rep;
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -112,7 +139,10 @@ void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,
         if (!midL)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -134,7 +164,10 @@ void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,
         }
     }
 
-    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == envRet)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnObserveListener::checkExAndRemoveListener(JNIEnv* env)
@@ -150,4 +183,4 @@ void JniOnObserveListener::checkExAndRemoveListener(JNIEnv* env)
     {
         m_ownerResource->removeOnObserveListener(env, m_jwListener);
     }
-}
\ No newline at end of file
+}
index 03e2ed8..7a220bf 100644 (file)
@@ -34,29 +34,41 @@ JniOnPlatformInfoListener::~JniOnPlatformInfoListener()
     LOGI("~JniOnPlatformInfoListener");
     if (m_jwListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
-        if (nullptr == env) return;
+        if (nullptr == env)
+        {
+            return;
+        }
 
         env->DeleteWeakGlobalRef(m_jwListener);
         m_jwListener = nullptr;
 
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
 }
 
 void JniOnPlatformInfoListener::foundPlatformCallback(const OC::OCRepresentation& ocRepresentation)
 {
-    jint ret;
+    jint ret = JNI_ERR;
     JNIEnv *env = GetJNIEnv(ret);
-    if (nullptr == env) return;
+    if (nullptr == env)
+    {
+        return;
+    }
 
     jobject jListener = env->NewLocalRef(m_jwListener);
     if (!jListener)
     {
         LOGI("Java onPlatformInfoListener object is already destroyed, quiting");
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -68,7 +80,10 @@ void JniOnPlatformInfoListener::foundPlatformCallback(const OC::OCRepresentation
     {
         delete rep;
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -77,7 +92,10 @@ void JniOnPlatformInfoListener::foundPlatformCallback(const OC::OCRepresentation
     {
         delete rep;
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
     jmethodID midL = env->GetMethodID(clsL, "onPlatformFound", "(Lorg/iotivity/base/OcRepresentation;)V");
@@ -85,7 +103,10 @@ void JniOnPlatformInfoListener::foundPlatformCallback(const OC::OCRepresentation
     {
         delete rep;
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -97,7 +118,10 @@ void JniOnPlatformInfoListener::foundPlatformCallback(const OC::OCRepresentation
         checkExAndRemoveListener(env);
     }
 
-    if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == ret)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnPlatformInfoListener::checkExAndRemoveListener(JNIEnv* env)
index 575748e..6a9bb06 100644 (file)
@@ -34,36 +34,51 @@ JniOnPostListener::~JniOnPostListener()
 {
     if (m_jwListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
-        if (nullptr == env) return;
+        if (nullptr == env)
+        {
+            return;
+        }
 
         env->DeleteWeakGlobalRef(m_jwListener);
         m_jwListener = nullptr;
 
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
 }
 
 void JniOnPostListener::onPostCallback(const HeaderOptions& headerOptions,
     const OCRepresentation& ocRepresentation, const int eCode)
 {
-    jint envRet;
+    jint envRet = JNI_ERR;
     JNIEnv *env = GetJNIEnv(envRet);
-    if (nullptr == env) return;
+    if (nullptr == env)
+    {
+        return;
+    }
 
     jobject jListener = env->NewLocalRef(m_jwListener);
     if (!jListener)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == envRet)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
     jclass clsL = env->GetObjectClass(jListener);
     if (!clsL)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == envRet)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -73,14 +88,20 @@ void JniOnPostListener::onPostCallback(const HeaderOptions& headerOptions,
         if (!ex)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
         jmethodID midL = env->GetMethodID(clsL, "onPostFailed", "(Ljava/lang/Throwable;)V");
         if (!midL)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
         env->CallVoidMethod(jListener, midL, ex);
@@ -91,7 +112,10 @@ void JniOnPostListener::onPostCallback(const HeaderOptions& headerOptions,
         if (!jHeaderOptionList)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -103,7 +127,10 @@ void JniOnPostListener::onPostCallback(const HeaderOptions& headerOptions,
         {
             delete rep;
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -112,7 +139,10 @@ void JniOnPostListener::onPostCallback(const HeaderOptions& headerOptions,
         if (!midL)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -125,7 +155,10 @@ void JniOnPostListener::onPostCallback(const HeaderOptions& headerOptions,
     }
 
     checkExAndRemoveListener(env);
-    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == envRet)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnPostListener::checkExAndRemoveListener(JNIEnv* env)
@@ -141,4 +174,4 @@ void JniOnPostListener::checkExAndRemoveListener(JNIEnv* env)
     {
         m_ownerResource->removeOnPostListener(env, m_jwListener);
     }
-}
\ No newline at end of file
+}
index 023c61d..9223250 100644 (file)
@@ -34,14 +34,20 @@ JniOnPresenceListener::~JniOnPresenceListener()
     LOGD("~JniOnPresenceListener");
     if (m_jwListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
-        if (nullptr == env) return;
+        if (nullptr == env)
+        {
+            return;
+        }
 
         env->DeleteWeakGlobalRef(m_jwListener);
         m_jwListener = nullptr;
 
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
 }
 
@@ -49,17 +55,26 @@ void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsig
     const std::string& hostAddress)
 {
     LOGI("JniOnPresenceListener::onPresenceCallback");
-    if (!m_jwListener) return;
+    if (!m_jwListener)
+    {
+        return;
+    }
 
-    jint ret;
+    jint ret = JNI_ERR;
     JNIEnv *env = GetJNIEnv(ret);
-    if (nullptr == env) return;
+    if (nullptr == env)
+    {
+        return;
+    }
 
     if (OC_STACK_OK != result && OC_STACK_PRESENCE_STOPPED != result &&
         OC_STACK_PRESENCE_TIMEOUT != result &&  OC_STACK_PRESENCE_DO_NOT_HANDLE != result)
     {
         ThrowOcException(result, "onPresenceCallback: stack failure");
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -67,7 +82,10 @@ void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsig
     if (enumField.empty())
     {
         ThrowOcException(JNI_INVALID_VALUE, "Unexpected OCStackResult value");
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -76,7 +94,10 @@ void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsig
     if (!jPresenceStatus)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -84,7 +105,10 @@ void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsig
     if (!jListener)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -92,7 +116,10 @@ void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsig
     if (!clsL)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
     jmethodID midL = env->GetMethodID(clsL, "onPresence",
@@ -100,7 +127,10 @@ void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsig
     if (!midL)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -111,7 +141,11 @@ void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsig
         LOGE("Java exception is thrown");
         checkExAndRemoveListener(env);
     }
-    if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+
+    if (JNI_EDETACHED == ret)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnPresenceListener::checkExAndRemoveListener(JNIEnv* env)
@@ -132,4 +166,4 @@ void JniOnPresenceListener::checkExAndRemoveListener(JNIEnv* env)
 jweak JniOnPresenceListener::getJWListener()
 {
     return this->m_jwListener;
-}
\ No newline at end of file
+}
index 7f375b9..961280a 100644 (file)
@@ -34,36 +34,51 @@ JniOnPutListener::~JniOnPutListener()
 {
     if (m_jwListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
-        if (nullptr == env) return;
+        if (nullptr == env)
+        {
+            return;
+        }
 
         env->DeleteWeakGlobalRef(m_jwListener);
         m_jwListener = nullptr;
 
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
 }
 
 void JniOnPutListener::onPutCallback(const HeaderOptions& headerOptions,
     const OCRepresentation& ocRepresentation, const int eCode)
 {
-    jint envRet;
+    jint envRet = JNI_ERR;
     JNIEnv *env = GetJNIEnv(envRet);
-    if (nullptr == env) return;
+    if (nullptr == env)
+    {
+        return;
+    }
 
     jobject jListener = env->NewLocalRef(m_jwListener);
     if (!jListener)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == envRet)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
     jclass clsL = env->GetObjectClass(jListener);
     if (!clsL)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == envRet)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -73,14 +88,20 @@ void JniOnPutListener::onPutCallback(const HeaderOptions& headerOptions,
         if (!ex)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
         jmethodID midL = env->GetMethodID(clsL, "onPutFailed", "(Ljava/lang/Throwable;)V");
         if (!midL)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
         env->CallVoidMethod(jListener, midL, ex);
@@ -91,7 +112,10 @@ void JniOnPutListener::onPutCallback(const HeaderOptions& headerOptions,
         if (!jHeaderOptionList)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -103,7 +127,10 @@ void JniOnPutListener::onPutCallback(const HeaderOptions& headerOptions,
         {
             delete rep;
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -113,7 +140,10 @@ void JniOnPutListener::onPutCallback(const HeaderOptions& headerOptions,
         if (!midL)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -126,7 +156,10 @@ void JniOnPutListener::onPutCallback(const HeaderOptions& headerOptions,
     }
 
     checkExAndRemoveListener(env);
-    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == envRet)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnPutListener::checkExAndRemoveListener(JNIEnv* env)
@@ -142,4 +175,4 @@ void JniOnPutListener::checkExAndRemoveListener(JNIEnv* env)
     {
         m_ownerResource->removeOnPutListener(env, m_jwListener);
     }
-}
\ No newline at end of file
+}
index cdc68d3..270b3f8 100644 (file)
@@ -34,35 +34,48 @@ JniOnResourceFoundListener::~JniOnResourceFoundListener()
     LOGI("~JniOnResourceFoundListener()");
     if (m_jwListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
-        if (nullptr == env) return;
+        if (nullptr == env)
+        {
+            return;
+        }
         env->DeleteWeakGlobalRef(m_jwListener);
         m_jwListener = nullptr;
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
 }
 
 void JniOnResourceFoundListener::foundResourceCallback(std::shared_ptr<OC::OCResource> resource)
 {
-    jint ret;
+    jint ret = JNI_ERR;
     JNIEnv *env = GetJNIEnv(ret);
-    if (nullptr == env) return;
+    if (nullptr == env)
+    {
+        return;
+    }
 
     jobject jListener = env->NewLocalRef(m_jwListener);
     if (!jListener)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
-        return;
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
 
     jobject jResource = env->NewObject(g_cls_OcResource, g_mid_OcResource_ctor);
     if (!jResource)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
-        return;
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
 
     JniOcResource *jniOcResource = new JniOcResource(resource);
@@ -71,24 +84,30 @@ void JniOnResourceFoundListener::foundResourceCallback(std::shared_ptr<OC::OCRes
     {
         delete jniOcResource;
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
-        return;
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
     jclass clsL = env->GetObjectClass(jListener);
     if (!clsL)
     {
         delete jniOcResource;
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
-        return;
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
     jmethodID midL = env->GetMethodID(clsL, "onResourceFound", "(Lorg/iotivity/base/OcResource;)V");
     if (!midL)
     {
         delete jniOcResource;
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
-        return;
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
     env->CallVoidMethod(jListener, midL, jResource);
     if (env->ExceptionCheck())
@@ -96,11 +115,16 @@ void JniOnResourceFoundListener::foundResourceCallback(std::shared_ptr<OC::OCRes
         LOGE("Java exception is thrown");
         delete jniOcResource;
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
-        return;
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
 
-    if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == ret)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnResourceFoundListener::checkExAndRemoveListener(JNIEnv* env)
@@ -116,4 +140,4 @@ void JniOnResourceFoundListener::checkExAndRemoveListener(JNIEnv* env)
     {
         m_removeListenerCallback(env, m_jwListener);
     }
-}
\ No newline at end of file
+}
index 55cdfba..12377d1 100644 (file)
@@ -32,40 +32,57 @@ JniPinCheckListener::~JniPinCheckListener()
     LOGI("~JniPinCheckListener()");
     if (m_jListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
-        if (NULL == env) return;
+        if (nullptr == env)
+        {
+            return;
+        }
         env->DeleteGlobalRef(m_jListener);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
 }
 
 void JniPinCheckListener::PinCallback(char *pinBuf, size_t bufSize)
 {
-    jint ret;
-
+    jint ret = JNI_ERR;
     JNIEnv *env = GetJNIEnv(ret);
-    if (NULL == env) return;
+    if (nullptr == env)
+    {
+        return;
+    }
 
     jclass clsL = env->GetObjectClass(m_jListener);
 
     if (!clsL)
     {
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
     jmethodID midL = env->GetMethodID(clsL, "pinCallbackListener", "()Ljava/lang/String;");
     if (!midL)
     {
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
     jstring jpin = (jstring)env->CallObjectMethod(m_jListener, midL);
     if (env->ExceptionCheck())
     {
         LOGE("Java exception is thrown");
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -73,5 +90,8 @@ void JniPinCheckListener::PinCallback(char *pinBuf, size_t bufSize)
     OICStrcpy(pinBuf, bufSize, str);
     env->ReleaseStringUTFChars(jpin, str);
 
-    if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == ret)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
index 6b9fd04..066a677 100644 (file)
@@ -35,26 +35,38 @@ JniProvisionResultListner::~JniProvisionResultListner()
     LOGI("~JniProvisionResultListner()");
     if (m_jwListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
-        if (NULL == env) return;
+        if (nullptr == env)
+        {
+            return;
+        }
         env->DeleteWeakGlobalRef(m_jwListener);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
     }
 }
 
 void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result, int hasError,
       ListenerFunc func)
 {
-    jint ret;
+    jint ret = JNI_ERR;
     JNIEnv *env = GetJNIEnv(ret);
-    if (NULL == env) return;
+    if (nullptr == env)
+    {
+        return;
+    }
 
     jobject jListener = env->NewLocalRef(m_jwListener);
     if (!jListener)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -63,7 +75,10 @@ void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result,
     if (!clsL)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -72,7 +87,10 @@ void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result,
     if (!jResultList)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -109,10 +127,19 @@ void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result,
             calledFunc = "provisionPairwiseDevicesListener";
         }
         break;
+        case ListenerFunc::PROVISIONDIRECTPAIRING:
+        {
+            calledFunc = "provisionDirectPairingListener";
+        }
+        break;
         default:
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == ret)
+            {
+                g_jvm->DetachCurrentThread();
+            }
+            return;
         }
         return;
     }
@@ -121,7 +148,10 @@ void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result,
     if (!midL)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
     env->CallVoidMethod(jListener, midL, jResultList, (jint)hasError);
@@ -131,7 +161,10 @@ void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result,
     }
 
     checkExAndRemoveListener(env);
-    if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == ret)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniProvisionResultListner::checkExAndRemoveListener(JNIEnv* env)
index 6df56d7..8bf5242 100644 (file)
@@ -35,7 +35,8 @@ enum class ListenerFunc
     PROVISIONCREDENTIALS,
     UNLINKDEVICES,
     REMOVEDEVICE,
-    PROVISIONPAIRWISEDEVICES
+    PROVISIONPAIRWISEDEVICES,
+    PROVISIONDIRECTPAIRING
 };
 
 class JniProvisionResultListner
index 24e4f57..8198e49 100644 (file)
@@ -232,3 +232,89 @@ OCStackResult JniSecureUtils::convertJavaACLToOCAcl(JNIEnv *env, jobject in, Oic
 
     return OC_STACK_OK;
 }
+
+OCStackResult JniSecureUtils::convertJavaPdACLToOCAcl(JNIEnv *env, jobject in, OicSecPdAcl_t *pdacl)
+{
+    jstring jData;
+    jvalue args[1];
+
+    jint jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecPdAcl_get_resources_cnt);
+    if (!jCount || env->ExceptionCheck())
+    {
+        return OC_STACK_ERROR;
+    }
+
+    pdacl->resourcesLen = jCount;
+    pdacl->resources = new char*[jCount];
+
+    if (!pdacl->resources)
+    {
+        return OC_STACK_ERROR;
+    }
+    for (jint i = 0; i < jCount; ++i)
+    {
+        args[0].i = i;
+        jData = (jstring) env->CallObjectMethodA(in, g_mid_OcOicSecPdAcl_get_resources, args);
+        if (!jData || env->ExceptionCheck())
+        {
+            return OC_STACK_ERROR;
+        }
+
+        pdacl->resources[i] = (char*) env->GetStringUTFChars(jData, 0);
+    }
+
+    jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecPdAcl_get_permission);
+    if (env->ExceptionCheck())
+    {
+        return OC_STACK_ERROR;
+    }
+
+    pdacl->permission = jCount;
+    jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecPdAcl_get_periods_cnt);
+    if (env->ExceptionCheck())
+    {
+        return OC_STACK_ERROR;
+    }
+
+    pdacl->prdRecrLen = jCount;
+    if (jCount)
+    {
+        pdacl->periods = new char*[jCount];
+        if (!pdacl->periods)
+        {
+            return OC_STACK_ERROR;
+        }
+    }
+    for (jint i = 0; i < jCount; ++i)
+    {
+        args[0].i = i;
+        jData = (jstring) env->CallObjectMethodA(in, g_mid_OcOicSecPdAcl_get_periods, args);
+        if (!jData || env->ExceptionCheck())
+        {
+            return OC_STACK_ERROR;
+        }
+
+        pdacl->periods[i] = (char*) env->GetStringUTFChars(jData, 0);
+    }
+
+    if (jCount)
+    {
+        pdacl->recurrences = new char*[jCount];
+        if (!pdacl->recurrences)
+        {
+            return OC_STACK_ERROR;
+        }
+    }
+    for (jint i = 0; i < jCount; ++i)
+    {
+        args[0].i = i;
+        jData = (jstring) env->CallObjectMethodA(in, g_mid_OcOicSecPdAcl_get_recurrences, args);
+        if (!jData ||  env->ExceptionCheck())
+        {
+            return OC_STACK_ERROR;
+        }
+
+        pdacl->recurrences[i] = (char*) env->GetStringUTFChars(jData, 0);
+    }
+    return OC_STACK_OK;
+}
index c239c44..c7226a5 100644 (file)
@@ -35,4 +35,5 @@ class JniSecureUtils
                 std::vector<std::shared_ptr<OC::OCSecureResource>>& deviceListVector);
         static jobject convertUUIDVectorToJavaStrList(JNIEnv *env, OC::UuidList_t &vector);
         static OCStackResult convertJavaACLToOCAcl(JNIEnv *env, jobject in, OicSecAcl_t *out);
+        static OCStackResult convertJavaPdACLToOCAcl(JNIEnv *env, jobject in, OicSecPdAcl_t *pdacl);
 };
index 4e3f276..3ee3ada 100644 (file)
 jobject JniUtils::convertStrVectorToJavaStrList(JNIEnv *env, std::vector<std::string> &vector)
 {
     jobject jList = env->NewObject(g_cls_LinkedList, g_mid_LinkedList_ctor);
-    if (!jList) return nullptr;
+    if (!jList)
+    {
+        return nullptr;
+    }
     for (size_t i = 0; i < vector.size(); ++i)
     {
         jstring jStr = env->NewStringUTF(vector[i].c_str());
-        if (!jStr) return nullptr;
+        if (!jStr)
+        {
+            return nullptr;
+        }
         env->CallBooleanMethod(jList, g_mid_LinkedList_add_object, jStr);
-        if (env->ExceptionCheck()) return nullptr;
+        if (env->ExceptionCheck())
+        {
+            return nullptr;
+        }
         env->DeleteLocalRef(jStr);
     }
     return jList;
@@ -40,15 +49,24 @@ jobject JniUtils::convertStrVectorToJavaStrList(JNIEnv *env, std::vector<std::st
 
 void JniUtils::convertJavaStrArrToStrVector(JNIEnv *env, jobjectArray jStrArr, std::vector<std::string> &vector)
 {
-    if (!jStrArr) return;
+    if (!jStrArr)
+    {
+        return;
+    }
 
     jsize len = env->GetArrayLength(jStrArr);
     for (jsize i = 0; i < len; ++i)
     {
         jstring jStr = (jstring)env->GetObjectArrayElement(jStrArr, i);
-        if (!jStr) return;
+        if (!jStr)
+        {
+            return;
+        }
         vector.push_back(env->GetStringUTFChars(jStr, nullptr));
-        if (env->ExceptionCheck()) return;
+        if (env->ExceptionCheck())
+        {
+            return;
+        }
         env->DeleteLocalRef(jStr);
     }
 }
@@ -56,12 +74,19 @@ void JniUtils::convertJavaStrArrToStrVector(JNIEnv *env, jobjectArray jStrArr, s
 void JniUtils::convertJavaHeaderOptionsArrToVector(JNIEnv *env, jobjectArray jHeaderOptions,
     OC::HeaderOptions &headerOptions)
 {
-    if (!jHeaderOptions) return;
+    if (!jHeaderOptions)
+    {
+        return;
+    }
+
     jsize len = env->GetArrayLength(jHeaderOptions);
     for (jsize i = 0; i < len; ++i)
     {
         jobject header = env->GetObjectArrayElement(jHeaderOptions, i);
-        if (!header) return;
+        if (!header)
+        {
+            return;
+        }
         jint jId = env->CallIntMethod(header, g_mid_OcHeaderOption_get_id);
         jstring jData = (jstring)env->CallObjectMethod(header, g_mid_OcHeaderOption_get_data);
         OC::HeaderOption::OCHeaderOption hopt(
@@ -70,7 +95,10 @@ void JniUtils::convertJavaHeaderOptionsArrToVector(JNIEnv *env, jobjectArray jHe
 
         headerOptions.push_back(hopt);
 
-        if (env->ExceptionCheck()) return;
+        if (env->ExceptionCheck())
+        {
+            return;
+        }
         env->DeleteLocalRef(header);
         env->DeleteLocalRef(jData);
     }
@@ -79,7 +107,10 @@ void JniUtils::convertJavaHeaderOptionsArrToVector(JNIEnv *env, jobjectArray jHe
 jobject JniUtils::convertHeaderOptionsVectorToJavaList(JNIEnv *env, const OC::HeaderOptions& headerOptions)
 {
     jobject jHeaderOptionList = env->NewObject(g_cls_LinkedList, g_mid_LinkedList_ctor);
-    if (!jHeaderOptionList) return nullptr;
+    if (!jHeaderOptionList)
+    {
+        return nullptr;
+    }
 
     for (size_t i = 0; i < headerOptions.size(); ++i)
     {
@@ -89,10 +120,16 @@ jobject JniUtils::convertHeaderOptionsVectorToJavaList(JNIEnv *env, const OC::He
             static_cast<jint>(headerOptions[i].getOptionID()),
             env->NewStringUTF(headerOptions[i].getOptionData().c_str())
             );
-        if (!jHeaderOption) return nullptr;
+        if (!jHeaderOption)
+        {
+            return nullptr;
+        }
 
         env->CallBooleanMethod(jHeaderOptionList, g_mid_LinkedList_add_object, jHeaderOption);
-        if (env->ExceptionCheck()) return nullptr;
+        if (env->ExceptionCheck())
+        {
+            return nullptr;
+        }
         env->DeleteLocalRef(jHeaderOption);
     }
 
@@ -101,25 +138,43 @@ jobject JniUtils::convertHeaderOptionsVectorToJavaList(JNIEnv *env, const OC::He
 
 void JniUtils::convertJavaMapToQueryParamsMap(JNIEnv *env, jobject hashMap, OC::QueryParamsMap &map)
 {
-    if (!hashMap) return;
+    if (!hashMap)
+    {
+        return;
+    }
 
     jobject jEntrySet = env->CallObjectMethod(hashMap, g_mid_Map_entrySet);
     jobject jIterator = env->CallObjectMethod(jEntrySet, g_mid_Set_iterator);
-    if (!jEntrySet || !jIterator || env->ExceptionCheck()) return;
+    if (!jEntrySet || !jIterator || env->ExceptionCheck())
+    {
+        return;
+    }
 
     while (env->CallBooleanMethod(jIterator, g_mid_Iterator_hasNext))
     {
         jobject jEntry = env->CallObjectMethod(jIterator, g_mid_Iterator_next);
-        if (!jEntry) return;
+        if (!jEntry)
+        {
+            return;
+        }
         jstring jKey = (jstring)env->CallObjectMethod(jEntry, g_mid_MapEntry_getKey);
-        if (!jKey) return;
+        if (!jKey)
+        {
+            return;
+        }
         jstring jValue = (jstring)env->CallObjectMethod(jEntry, g_mid_MapEntry_getValue);
-        if (!jValue) return;
+        if (!jValue)
+        {
+            return;
+        }
 
         map.insert(std::make_pair(env->GetStringUTFChars(jKey, nullptr),
             env->GetStringUTFChars(jValue, nullptr)));
 
-        if (env->ExceptionCheck()) return;
+        if (env->ExceptionCheck())
+        {
+            return;
+        }
         env->DeleteLocalRef(jEntry);
         env->DeleteLocalRef(jKey);
         env->DeleteLocalRef(jValue);
@@ -129,7 +184,10 @@ void JniUtils::convertJavaMapToQueryParamsMap(JNIEnv *env, jobject hashMap, OC::
 jobject JniUtils::convertQueryParamsMapToJavaMap(JNIEnv *env, const OC::QueryParamsMap &map)
 {
     jobject hashMap = env->NewObject(g_cls_HashMap, g_mid_HashMap_ctor);
-    if (!hashMap) return nullptr;
+    if (!hashMap)
+    {
+        return nullptr;
+    }
 
     for (auto it = map.begin(); it != map.end(); ++it)
     {
@@ -140,7 +198,10 @@ jobject JniUtils::convertQueryParamsMapToJavaMap(JNIEnv *env, const OC::QueryPar
             g_mid_HashMap_put,
             env->NewStringUTF(key.c_str()),
             env->NewStringUTF(value.c_str()));
-        if (env->ExceptionCheck()) return nullptr;
+        if (env->ExceptionCheck())
+        {
+            return nullptr;
+        }
     }
 
     return hashMap;
@@ -150,16 +211,25 @@ void JniUtils::convertJavaRepresentationArrToVector(JNIEnv *env,
     jobjectArray jRepresentationArray,
     std::vector<OC::OCRepresentation>& representationVector)
 {
-    if (!jRepresentationArray) return;
+    if (!jRepresentationArray)
+    {
+        return;
+    }
     jsize len = env->GetArrayLength(jRepresentationArray);
 
     for (jsize i = 0; i < len; ++i)
     {
         jobject jRep = env->GetObjectArrayElement(jRepresentationArray, i);
-        if (!jRep) return;
+        if (!jRep)
+        {
+            return;
+        }
         OC::OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, jRep);
         representationVector.push_back(*rep);
-        if (env->ExceptionCheck()) return;
+        if (env->ExceptionCheck())
+        {
+            return;
+        }
         env->DeleteLocalRef(jRep);
     }
 }
@@ -169,7 +239,10 @@ jobjectArray JniUtils::convertRepresentationVectorToJavaArray(JNIEnv *env,
 {
     jsize len = static_cast<jsize>(representationVector.size());
     jobjectArray repArr = env->NewObjectArray(len, g_cls_OcRepresentation, nullptr);
-    if (!repArr) return nullptr;
+    if (!repArr)
+    {
+        return nullptr;
+    }
     for (jsize i = 0; i < len; ++i)
     {
         OCRepresentation* rep = new OCRepresentation(representationVector[i]);
@@ -182,9 +255,12 @@ jobjectArray JniUtils::convertRepresentationVectorToJavaArray(JNIEnv *env,
             return nullptr;
         }
         env->SetObjectArrayElement(repArr, i, jRepresentation);
-        if (env->ExceptionCheck()) return nullptr;
+        if (env->ExceptionCheck())
+        {
+            return nullptr;
+        }
         env->DeleteLocalRef(jRepresentation);
     }
 
     return repArr;
-}
\ No newline at end of file
+}
index fcfa2a1..a7a259a 100644 (file)
@@ -47,84 +47,89 @@ public:
 
     static OC::ServiceType getServiceType(JNIEnv *env, int type)
     {
-        switch (type) {
-        case 0:
-            return OC::ServiceType::InProc;
-        case 1:
-            return OC::ServiceType::OutOfProc;
-        default:
-            ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected service type");
-            return OC::ServiceType::OutOfProc;
+        switch (type)
+        {
+            case 0:
+                return OC::ServiceType::InProc;
+            case 1:
+                return OC::ServiceType::OutOfProc;
+            default:
+                ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected service type");
+                return OC::ServiceType::OutOfProc;
         };
     }
 
     static OC::ModeType getModeType(JNIEnv *env, int type)
     {
-        switch (type) {
-        case 0:
-            return OC::ModeType::Server;
-        case 1:
-            return OC::ModeType::Client;
-        case 2:
-            return OC::ModeType::Both;
-        case 3:
-            return OC::ModeType::Gateway;
-        default:
-            ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected mode type");
-            return OC::ModeType::Both;
+        switch (type)
+        {
+            case 0:
+                return OC::ModeType::Server;
+            case 1:
+                return OC::ModeType::Client;
+            case 2:
+                return OC::ModeType::Both;
+            case 3:
+                return OC::ModeType::Gateway;
+            default:
+                ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected mode type");
+                return OC::ModeType::Both;
         };
     }
 
     static OC::QualityOfService getQOS(JNIEnv *env, int type)
     {
-        switch (type) {
-        case 0:
-            return OC::QualityOfService::LowQos;
-        case 1:
-            return OC::QualityOfService::MidQos;
-        case 2:
-            return OC::QualityOfService::HighQos;
-        case 3:
-            return OC::QualityOfService::NaQos;
-        default:
-            ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected quality of service");
-            return OC::QualityOfService::NaQos;
+        switch (type)
+        {
+            case 0:
+                return OC::QualityOfService::LowQos;
+            case 1:
+                return OC::QualityOfService::MidQos;
+            case 2:
+                return OC::QualityOfService::HighQos;
+            case 3:
+                return OC::QualityOfService::NaQos;
+            default:
+                ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected quality of service");
+                return OC::QualityOfService::NaQos;
         };
     }
 
     static OC::ObserveType getObserveType(JNIEnv *env, int type)
     {
-        switch (type) {
-        case 0:
-            return OC::ObserveType::Observe;
-        case 1:
-            return OC::ObserveType::ObserveAll;
-        default:
-            ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected observe type");
-            return OC::ObserveType::ObserveAll;
+        switch (type)
+        {
+            case 0:
+                return OC::ObserveType::Observe;
+            case 1:
+                return OC::ObserveType::ObserveAll;
+            default:
+                ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected observe type");
+                return OC::ObserveType::ObserveAll;
         };
     }
 
     static OCEntityHandlerResult getOCEntityHandlerResult(JNIEnv *env, int type)
     {
-        switch (type) {
-        case 0:
-            return OCEntityHandlerResult::OC_EH_OK;
-        case 1:
-            return OCEntityHandlerResult::OC_EH_ERROR;
-        case 2:
-            return OCEntityHandlerResult::OC_EH_RESOURCE_CREATED;
-        case 3:
-            return OCEntityHandlerResult::OC_EH_RESOURCE_DELETED;
-        case 4:
-            return OCEntityHandlerResult::OC_EH_SLOW;
-        case 5:
-            return OCEntityHandlerResult::OC_EH_FORBIDDEN;
-        case 6:
-            return OCEntityHandlerResult::OC_EH_RESOURCE_NOT_FOUND;
-        default:
-            ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected OCEntityHandlerResult");
-            return OCEntityHandlerResult::OC_EH_ERROR;
+        switch (type)
+        {
+            case 0:
+                return OCEntityHandlerResult::OC_EH_OK;
+            case 1:
+                return OCEntityHandlerResult::OC_EH_ERROR;
+            case 2:
+                return OCEntityHandlerResult::OC_EH_RESOURCE_CREATED;
+            case 3:
+                return OCEntityHandlerResult::OC_EH_RESOURCE_DELETED;
+            case 4:
+                return OCEntityHandlerResult::OC_EH_SLOW;
+            case 5:
+                return OCEntityHandlerResult::OC_EH_FORBIDDEN;
+            case 6:
+                return OCEntityHandlerResult::OC_EH_RESOURCE_NOT_FOUND;
+            default:
+                ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected OCEntityHandlerResult");
+                return OCEntityHandlerResult::OC_EH_ERROR;
         };
     }
 
@@ -132,106 +137,106 @@ public:
     {
         switch (result)
         {
-        /** Success status code - START HERE.*/
-        case OC_STACK_OK:
-            return "OK";
-        case OC_STACK_RESOURCE_CREATED:
-            return "RESOURCE_CREATED";
-        case OC_STACK_RESOURCE_DELETED:
-            return "RESOURCE_DELETED";
-        case OC_STACK_CONTINUE:
-            return "CONTINUE";
-        /* Error status code - START HERE */
-        case OC_STACK_INVALID_URI:
-            return "INVALID_URI";
-        case OC_STACK_INVALID_QUERY:
-            return "INVALID_QUERY";
-        case OC_STACK_INVALID_IP:
-            return "INVALID_IP";
-        case OC_STACK_INVALID_PORT:
-            return "INVALID_PORT";
-        case OC_STACK_INVALID_CALLBACK:
-            return "INVALID_CALLBACK";
-        case OC_STACK_INVALID_METHOD:
-            return "INVALID_METHOD";
-        /** Invalid parameter.*/
-        case OC_STACK_INVALID_PARAM:
-            return "INVALID_PARAM";
-        case OC_STACK_INVALID_OBSERVE_PARAM:
-            return "INVALID_OBSERVE_PARAM";
-        case OC_STACK_NO_MEMORY:
-            return "NO_MEMORY";
-        case OC_STACK_COMM_ERROR:
-            return "COMM_ERROR";
-        case OC_STACK_TIMEOUT:
-            return "TIMEOUT";
-        case OC_STACK_ADAPTER_NOT_ENABLED:
-            return "ADAPTER_NOT_ENABLED";
-        case OC_STACK_NOTIMPL:
-            return "NOTIMPL";
-        /** Resource not found.*/
-        case OC_STACK_NO_RESOURCE:
-            return "NO_RESOURCE";
-        /** e.g: not supported method or interface.*/
-        case  OC_STACK_RESOURCE_ERROR:
-            return "RESOURCE_ERROR";
-        case OC_STACK_SLOW_RESOURCE:
-            return "SLOW_RESOURCE";
-        case OC_STACK_DUPLICATE_REQUEST:
-            return "DUPLICATE_REQUEST";
-        /** Resource has no registered observers.*/
-        case OC_STACK_NO_OBSERVERS:
-            return "NO_OBSERVERS";
-        case OC_STACK_OBSERVER_NOT_FOUND:
-            return "OBSERVER_NOT_FOUND";
-        case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
-            return "VIRTUAL_DO_NOT_HANDLE";
-        case OC_STACK_INVALID_OPTION:
-            return "INVALID_OPTION";
-        /** The remote reply contained malformed data.*/
-        case OC_STACK_MALFORMED_RESPONSE:
-            return "MALFORMED_RESPONSE";
-        case OC_STACK_PERSISTENT_BUFFER_REQUIRED:
-            return "PERSISTENT_BUFFER_REQUIRED";
-        case OC_STACK_INVALID_REQUEST_HANDLE:
-            return "INVALID_REQUEST_HANDLE";
-        case OC_STACK_INVALID_DEVICE_INFO:
-            return "INVALID_DEVICE_INFO";
-        case OC_STACK_INVALID_JSON:
-            return "INVALID_JSON";
-        /** Request is not authorized by Resource Server. */
-        case OC_STACK_UNAUTHORIZED_REQ:
-            return "UNAUTHORIZED_REQ";
-        /** Error code from PDM */
-        case OC_STACK_PDM_IS_NOT_INITIALIZED:
-            return "PDM_IS_NOT_INITIALIZED";
-        case OC_STACK_DUPLICATE_UUID:
-            return "DUPLICATE_UUID";
-        case OC_STACK_INCONSISTENT_DB:
-            return "INCONSISTENT_DB";
-        /** Error code from OTM */
-        case OC_STACK_AUTHENTICATION_FAILURE:
-            return "AUTHENTICATION_FAILURE";
-        /** Insert all new error codes here!.*/
+            /** Success status code - START HERE.*/
+            case OC_STACK_OK:
+                return "OK";
+            case OC_STACK_RESOURCE_CREATED:
+                return "RESOURCE_CREATED";
+            case OC_STACK_RESOURCE_DELETED:
+                return "RESOURCE_DELETED";
+            case OC_STACK_CONTINUE:
+                return "CONTINUE";
+            /* Error status code - START HERE */
+            case OC_STACK_INVALID_URI:
+                return "INVALID_URI";
+            case OC_STACK_INVALID_QUERY:
+                return "INVALID_QUERY";
+            case OC_STACK_INVALID_IP:
+                return "INVALID_IP";
+            case OC_STACK_INVALID_PORT:
+                return "INVALID_PORT";
+            case OC_STACK_INVALID_CALLBACK:
+                return "INVALID_CALLBACK";
+            case OC_STACK_INVALID_METHOD:
+                return "INVALID_METHOD";
+            /** Invalid parameter.*/
+            case OC_STACK_INVALID_PARAM:
+                return "INVALID_PARAM";
+            case OC_STACK_INVALID_OBSERVE_PARAM:
+                return "INVALID_OBSERVE_PARAM";
+            case OC_STACK_NO_MEMORY:
+                return "NO_MEMORY";
+            case OC_STACK_COMM_ERROR:
+                return "COMM_ERROR";
+            case OC_STACK_TIMEOUT:
+                return "TIMEOUT";
+            case OC_STACK_ADAPTER_NOT_ENABLED:
+                return "ADAPTER_NOT_ENABLED";
+            case OC_STACK_NOTIMPL:
+                return "NOTIMPL";
+            /** Resource not found.*/
+            case OC_STACK_NO_RESOURCE:
+                return "NO_RESOURCE";
+            /** e.g: not supported method or interface.*/
+            case  OC_STACK_RESOURCE_ERROR:
+                return "RESOURCE_ERROR";
+            case OC_STACK_SLOW_RESOURCE:
+                return "SLOW_RESOURCE";
+            case OC_STACK_DUPLICATE_REQUEST:
+                return "DUPLICATE_REQUEST";
+            /** Resource has no registered observers.*/
+            case OC_STACK_NO_OBSERVERS:
+                return "NO_OBSERVERS";
+            case OC_STACK_OBSERVER_NOT_FOUND:
+                return "OBSERVER_NOT_FOUND";
+            case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
+                return "VIRTUAL_DO_NOT_HANDLE";
+            case OC_STACK_INVALID_OPTION:
+                return "INVALID_OPTION";
+            /** The remote reply contained malformed data.*/
+            case OC_STACK_MALFORMED_RESPONSE:
+                return "MALFORMED_RESPONSE";
+            case OC_STACK_PERSISTENT_BUFFER_REQUIRED:
+                return "PERSISTENT_BUFFER_REQUIRED";
+            case OC_STACK_INVALID_REQUEST_HANDLE:
+                return "INVALID_REQUEST_HANDLE";
+            case OC_STACK_INVALID_DEVICE_INFO:
+                return "INVALID_DEVICE_INFO";
+            case OC_STACK_INVALID_JSON:
+                return "INVALID_JSON";
+            /** Request is not authorized by Resource Server. */
+            case OC_STACK_UNAUTHORIZED_REQ:
+                return "UNAUTHORIZED_REQ";
+            /** Error code from PDM */
+            case OC_STACK_PDM_IS_NOT_INITIALIZED:
+                return "PDM_IS_NOT_INITIALIZED";
+            case OC_STACK_DUPLICATE_UUID:
+                return "DUPLICATE_UUID";
+            case OC_STACK_INCONSISTENT_DB:
+                return "INCONSISTENT_DB";
+            /** Error code from OTM */
+            case OC_STACK_AUTHENTICATION_FAILURE:
+                return "AUTHENTICATION_FAILURE";
+            /** Insert all new error codes here!.*/
 #ifdef WITH_PRESENCE
-        case OC_STACK_PRESENCE_STOPPED:
-            return "PRESENCE_STOPPED";
-        case OC_STACK_PRESENCE_TIMEOUT:
-            return "PRESENCE_TIMEOUT";
-        case OC_STACK_PRESENCE_DO_NOT_HANDLE:
-            return "PRESENCE_DO_NOT_HANDLE";
+            case OC_STACK_PRESENCE_STOPPED:
+                return "PRESENCE_STOPPED";
+            case OC_STACK_PRESENCE_TIMEOUT:
+                return "PRESENCE_TIMEOUT";
+            case OC_STACK_PRESENCE_DO_NOT_HANDLE:
+                return "PRESENCE_DO_NOT_HANDLE";
 #endif
-        case OC_STACK_ERROR:
-            return "ERROR";
+            case OC_STACK_ERROR:
+                return "ERROR";
 
-        case JNI_EXCEPTION:
-            return "JNI_EXCEPTION";
-        case JNI_NO_NATIVE_POINTER:
-            return "JNI_NO_NATIVE_POINTER";
-        case JNI_INVALID_VALUE:
-            return "JNI_INVALID_VALUE";
-        default:
-            return "";
+            case JNI_EXCEPTION:
+                return "JNI_EXCEPTION";
+            case JNI_NO_NATIVE_POINTER:
+                return "JNI_NO_NATIVE_POINTER";
+            case JNI_INVALID_VALUE:
+                return "JNI_INVALID_VALUE";
+            default:
+                return "";
         }
     }
 };
index 3ab7dd2..d6a67c7 100644 (file)
@@ -25,6 +25,7 @@ package org.iotivity.base;
 import android.test.InstrumentationTestCase;
 import android.util.Log;
 
+import java.util.Arrays;
 import java.util.Date;
 import java.util.EnumSet;
 import java.util.HashMap;
@@ -1048,7 +1049,10 @@ public class SmokeTest extends InstrumentationTestCase {
             }
         };
 
-        OcDeviceInfo devInfo = new OcDeviceInfo("myDeviceName");
+        OcDeviceInfo devInfo = new OcDeviceInfo(
+                "myDeviceName",
+                Arrays.asList(new String[]{"oic.d.test"})
+        );
 
         try {
             //server
index acb4cfa..4320ad1 100644 (file)
 
 package org.iotivity.base;
 
+import java.util.List;
+
 /**
- * This class is expected as input for device properties. Device name is mandatory and expected
- * from the application. Device id of type UUID will be generated by the stack.
+ * This class is expected as input for device properties. Device name and types are mandatory
+ * and expected from the application. Device id of type UUID will be generated by the stack.
  */
 public class OcDeviceInfo {
 
     private String mDeviceName;
+    private List<String> mDeviceTypes;
 
-    public OcDeviceInfo(String deviceName) {
-
+    public OcDeviceInfo(String deviceName, List<String> deviceTypes) {
         this.mDeviceName = deviceName;
+        this.mDeviceTypes = deviceTypes;
     }
 
     public String getDeviceName() {
         return mDeviceName;
     }
+
+    public List<String> getDeviceTypes() {
+        return mDeviceTypes;
+    }
 }
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcDirectPairDevice.java b/android/android_api/base/src/main/java/org/iotivity/base/OcDirectPairDevice.java
new file mode 100644 (file)
index 0000000..aff3238
--- /dev/null
@@ -0,0 +1,113 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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;
+
+import java.util.List;
+import java.util.EnumSet;
+import java.util.Map;
+import java.util.Arrays;
+import java.util.ArrayList;
+
+public class OcDirectPairDevice {
+
+
+    private long mNativeHandle;
+    private String mdeviceID;
+    private String mHost;
+
+    private OcDirectPairDevice(long nativeHandle) {
+        this.mNativeHandle = nativeHandle;
+    }
+
+    public OcDirectPairDevice(String deviceID)
+    {
+        this.mdeviceID = deviceID;
+    }
+
+    public String getDevId()
+    {
+        return this.mdeviceID;
+    }
+
+    public native String getHost();
+
+    public List<Integer> getPairingMethodList() {
+        int [] intList = this.getPairingMethods();
+        List<Integer> prmList = new ArrayList<Integer>();
+        for (int i = 0; i < intList.length; i++)
+        {
+            prmList.add(intList[i]);
+        }
+        return  prmList;
+    }
+
+    private native int[] getPairingMethods();
+
+    /**
+     * Method to get the connectivity type of this resource
+     *
+     * @return EnumSet<OcConnectivityType></OcConnectivityType> connectivity type set
+     */
+    public EnumSet<OcConnectivityType> getConnectivityTypeSet() {
+        return OcConnectivityType.convertToEnumSet(
+                this.getConnectivityTypeN()
+        );
+    }
+
+    private native int getConnectivityTypeN();
+
+
+    /**
+     *  Method to get list of all paired devices for a given device.
+     *
+     *  @param GetDirectPairedListener Callback function, which will receive the list of direct paired devices.
+     *  @throws OcException
+     */
+
+    public native void getDirectPairedDevices(GetDirectPairedListener getDirectPairedListener) throws OcException;
+
+    public interface GetDirectPairedListener {
+        public void getDirectPairedListener(List<String> ocPairedDeviceList);
+    }
+
+    /**
+     *  Method to perform direct pairing between two devices.
+     *
+     *  @param DirectPairingListener Callback function, which will be called after
+     *                                      completion of direct pairing.
+     *  @throws OcException
+     */
+    public native void doDirectPairing(OcDirectPairDevice peer,
+            OcPrmType pmSel, String pinNumber,
+            DirectPairingListener directPairingListener) throws OcException;
+
+
+    public interface DirectPairingListener {
+        public void directPairingListener(String devId, int result);
+    }
+
+    @Override
+    public String toString() {
+        return this.mdeviceID;
+    }
+}
index d08b1c6..fc69e48 100644 (file)
@@ -541,12 +541,16 @@ public final class OcPlatform {
             OcDeviceInfo ocDeviceInfo) throws OcException {
         OcPlatform.initCheck();
         OcPlatform.registerDeviceInfo0(
-                ocDeviceInfo.getDeviceName()
+                ocDeviceInfo.getDeviceName(),
+                ocDeviceInfo.getDeviceTypes().toArray(
+                        new String[ocDeviceInfo.getDeviceTypes().size()]
+                )
         );
     }
 
     private static native void registerDeviceInfo0(
-            String deviceName
+            String deviceName,
+            String[] deviceTypes
     ) throws OcException;
 
     /**
@@ -897,6 +901,81 @@ public final class OcPlatform {
             throws OcException;
 
     /**
+     *  Method to find all devices which are eligible for direct pairing and return the list.
+     *
+     *  @param timeout timeout for discovering direct pair devices.
+     *  @param FindDirectPairingListener Callback function, which will receive the list of direct
+     *                                  pairable devices.
+     *  @throws OcException
+     */
+   public static native void findDirectPairingDevices(int timeout,
+            FindDirectPairingListener onFindDirectPairingListener) throws OcException;
+
+    /**
+     *  Method to get list of all paired devices for a given device.
+     *
+     *  @param GetDirectPairedListener Callback function, which will receive the list of direct
+     *                                 paired devices.
+     *  @throws OcException
+     */
+    public native void getDirectPairedDevices(GetDirectPairedListener onGetDirectPairedListener)
+        throws OcException;
+
+    /**
+     *  Method to perform direct pairing between two devices.
+     *
+     *  @param peer  Target peer
+     *  @param prmType Pairing Method to be used for Pairing
+     *  @param pin pin
+     *  @param DirectPairingListener Callback function, which will be called after
+     *                                      completion of direct pairing.
+     *  @throws OcException
+     */
+    public static void doDirectPairing(
+            OcDirectPairDevice peer,
+            OcPrmType prmType,
+            String pin,
+            DirectPairingListener onDirectPairingListener) throws OcException {
+
+        OcPlatform.doDirectPairing0(
+                peer,
+                prmType.getValue(),
+                pin,
+                onDirectPairingListener
+                );
+    }
+
+    private static native void doDirectPairing0(OcDirectPairDevice peer,
+            int pmSel, String pinNumber, DirectPairingListener onDirectPairingListener)
+    throws OcException;
+
+    /**
+     * An FindDirectPairingListener can be registered via the OcPlatform.findDirectPairingDevices call.
+     * Event listeners are notified asynchronously
+     */
+    public interface FindDirectPairingListener {
+        public void onFindDirectPairingListener(List<OcDirectPairDevice> ocPairedDeviceList);
+    }
+
+    /**
+     * Listerner to Get List of already Direct Paired devices.
+     * An GetDirectPairedListener can be registered via the OcPlatform.getDirectPairedDevices call.
+     * Event listeners are notified asynchronously
+     */
+    public interface GetDirectPairedListener {
+        public void onGetDirectPairedListener(List<OcDirectPairDevice> ocPairedDeviceList);
+    }
+
+    /**
+     * Listner to get result of doDirectPairing.
+     * An DirectPairingListener can be registered via the OcPlatform.doDirectPairing call.
+     * Event listeners are notified asynchronously
+     */
+    public interface DirectPairingListener {
+        public void onDirectPairingListener(String devId, int result);
+    }
+
+    /**
      * An OnResourceFoundListener can be registered via the OcPlatform.findResource call.
      * Event listeners are notified asynchronously
      */
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcPrmType.java b/android/android_api/base/src/main/java/org/iotivity/base/OcPrmType.java
new file mode 100755 (executable)
index 0000000..2c2b37f
--- /dev/null
@@ -0,0 +1,58 @@
+/*\r
+ * //******************************************************************\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
+/**\r
+ * @brief   direct pairing Method Type.\r
+ *              0:  not allowed\r
+ *              1:  pre-configured pin\r
+ *              2:  random pin\r
+ */\r
+package org.iotivity.base;\r
+\r
+public enum OcPrmType {\r
+    DP_INVALID           (-1),\r
+    DP_NOT_ALLOWED       (0),\r
+    DP_PRE_CONFIGURED    (1 << 0),\r
+    DP_RANDOM_PIN        (1 << 1);\r
+\r
+    private int value;\r
+\r
+    private OcPrmType(int value) {\r
+        this.value = value;\r
+    }\r
+\r
+    public int getValue() {\r
+        return this.value;\r
+    }\r
+\r
+    public static OcPrmType convertOcPrmType(int value) {\r
+        switch (value)\r
+        {\r
+            case 0:\r
+                return OcPrmType.DP_NOT_ALLOWED;\r
+            case 1:\r
+                return OcPrmType.DP_PRE_CONFIGURED;\r
+            case 2:\r
+                return OcPrmType.DP_RANDOM_PIN;\r
+        }\r
+        return OcPrmType.DP_INVALID;\r
+    }\r
+}\r
index 0be617a..24d8b88 100644 (file)
@@ -25,6 +25,7 @@ package org.iotivity.base;
 import java.security.InvalidParameterException;
 import java.util.Arrays;
 import java.util.List;
+import java.util.Map;
 
 /**
  *
@@ -52,6 +53,8 @@ public class OcRepresentation {
         this.mNativeNeedsDelete = nativeNeedsDelete;
     }
 
+    public native Map<String, Object> getValues();
+
     public <T> T getValue(String key) throws OcException {
         Object obj = this.getValueN(key);
         @SuppressWarnings("unchecked")
index 368eda9..f69b548 100644 (file)
@@ -131,6 +131,46 @@ public class OcSecureResource {
             ProvisionPairwiseDevicesListener provisionPairwiseDevicesListener) throws OcException;
 
     /**
+     *  Method to configure resource for direct pairing
+     *
+     *  @param pin                      pin number
+     *  @param pdacls                   Array of Device Pairing Access Control List
+     *  @param type                     List of supported OcPrmType
+     *  @param edp                      enable (1) / disable (0)
+     *  @param ProvisionDirectPairing   Callback function, which will be called after completion
+     *                                  of Direct Pairing.
+     *  @throws OcException
+     */
+
+    public void doProvisionDirectPairing(String pin, OicSecPdAcl[] pdacls, List<OcPrmType> type,
+            boolean edp , ProvisionDirectPairingListener provisionDirectPairingListener)
+        throws OcException {
+
+            int[] typeArray = new int[type.size()];
+            int i = 0;
+            for (OcPrmType ocPrmType:type) {
+                typeArray[i++] = ocPrmType.getValue();
+            }
+
+            this.provisionDirectPairing(pin, pdacls, typeArray, (edp?1:0),
+                    provisionDirectPairingListener);
+        }
+
+    private native void provisionDirectPairing(String pin, OicSecPdAcl[] pdacls, int[] type,
+            int edp , ProvisionDirectPairingListener provisionDirectPairingListener)
+        throws OcException;
+
+    /**
+     * provisionDirectPairingListener can be registered with doOwnershipTransfer
+     * call.
+     * Listener notified asynchronously.
+     */
+    public interface ProvisionDirectPairingListener {
+        public void provisionDirectPairingListener(List<ProvisionResult> provisionResultList,
+                int hasError);
+    }
+
+    /**
      * doOwnershipTransferListener can be registered with doOwnershipTransfer
      * call.
      * Listener notified asynchronously.
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OicSecPdAcl.java b/android/android_api/base/src/main/java/org/iotivity/base/OicSecPdAcl.java
new file mode 100644 (file)
index 0000000..5768123
--- /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.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base;
+
+import java.io.Serializable;
+import java.util.List;
+import java.util.Arrays;
+
+public class OicSecPdAcl implements Serializable {
+
+    private int          mPermission;
+    private List<String> mResources;
+    private List<String> mPeriods;
+    private List<String> mRecurrences;
+
+    public OicSecPdAcl(List<String> recurrences, List<String> periods, int permission,
+            List<String> resources) {
+        this.mRecurrences = recurrences;
+        this.mPeriods = periods;
+        this.mPermission = permission;
+        this.mResources = resources;
+    }
+
+    public List<String> getRecurrences() {
+        return mRecurrences;
+    }
+
+    public void setRecurrences(List<String> recurrences) {
+        this.mRecurrences = recurrences;
+    }
+
+    public List<String> getPeriods() {
+        return mPeriods;
+    }
+
+    public void setPeriods(List<String> periods) {
+        this.mPeriods = periods;
+    }
+
+    public int getPermission() {
+        return this.mPermission;
+    }
+
+    public void setPermission(int permission) {
+        this.mPermission = permission;
+    }
+
+    public List<String> getResources() {
+        return mResources;
+    }
+
+    public void setResources(List<String> resources) {
+        this.mResources = resources;
+    }
+
+    public int getResourcesCount() {
+        return this.mResources.size();
+    }
+
+    public String getResources(int i) {
+        return this.mResources.get(i);
+    }
+
+    public int getPeriodsCount() {
+        return this.mPeriods.size();
+    }
+
+    public String getPeriods(int i) {
+        return this.mPeriods.get(i);
+    }
+
+    public String getRecurrences(int i) {
+        return this.mRecurrences.get(i);
+    }
+}
index 57b8738..e06d574 100644 (file)
@@ -31,7 +31,9 @@ public class CaBtPairingInterface {
     private static Context mContext;
 
     private CaBtPairingInterface(Context context) {
-        mContext = context;
+        synchronized(CaBtPairingInterface.class) {
+            mContext = context;
+        }
         registerIntentFilter();
     }
 
index a24e1f3..aaf8bc6 100644 (file)
@@ -32,7 +32,9 @@ public class CaEdrInterface {
     private static Context mContext;
 
     private CaEdrInterface(Context context) {
-        mContext = context;
+        synchronized(CaEdrInterface.class) {
+            mContext = context;
+        }
         registerIntentFilter();
     }
 
index 7771ba1..3d62800 100644 (file)
@@ -177,4 +177,19 @@ public class CaInterface {
     private static native void caBtPairingStartScan();
     private static native void caBtPairingStopScan();
     private static native void caBtPairingCreateBond(BluetoothDevice device);
+
+    /**
+     *  set BLE scan interval time and working count.
+     *  scanning logic (start scan -> stop scan) will be worked repeatly for workingCount.
+     *  and if you choose '0' value for workingCount parameter,
+     *  scanning will be worked continually as interval time.
+     *  @param intervalTime                  interval time(Seconds).
+     *  @param workingCount                  working count with interval time.
+     */
+
+    public synchronized static void setLeScanIntervalTime(int intervalTime, int workingCount){
+        CaInterface.setLeScanIntervalTimeImpl(intervalTime, workingCount);
+    }
+
+    private static native void setLeScanIntervalTimeImpl(int intervalTime, int workingCount);
 }
index 2314df9..a747953 100644 (file)
@@ -53,7 +53,9 @@ public class CaIpInterface {
     }\r
 \r
     private CaIpInterface(Context context) {\r
-        mContext = context;\r
+        synchronized(CaIpInterface.class) {\r
+            mContext = context;\r
+        }\r
         registerIpStateReceiver();\r
     }\r
 \r
index 0aac643..695359b 100644 (file)
@@ -47,10 +47,14 @@ public class CaLeClientInterface {
     private CaLeClientInterface(Context context) {
         caLeRegisterLeScanCallback(mLeScanCallback);
         caLeRegisterGattCallback(mGattCallback);
-        mContext = context;
+        synchronized(CaLeClientInterface.class) {
+            mContext = context;
+        }
         registerIntentFilter();
     }
 
+
+
     public static void getLeScanCallback() {
         caLeRegisterLeScanCallback(mLeScanCallback);
     }
index ebb273b..dee2ac1 100644 (file)
@@ -49,7 +49,9 @@ public class CaNfcInterface implements NfcAdapter.CreateNdefMessageCallback {
 
     private CaNfcInterface(Context context, Activity activity) {
         Log.d(MYTAG, "NFC  registerNfcReceiver");
-        mContext = context;
+        synchronized(CaNfcInterface.class) {
+            mContext = context;
+        }
         mActivity = activity;
 
         mAdapter = NfcAdapter.getDefaultAdapter(mContext);
diff --git a/android/examples/DirectPairing/.classpath b/android/examples/DirectPairing/.classpath
new file mode 100644 (file)
index 0000000..26bdfa6
--- /dev/null
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+       <classpathentry kind="src" path="src"/>\r
+       <classpathentry kind="src" path="gen"/>\r
+       <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>\r
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>\r
+       <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>\r
+       <classpathentry kind="output" path="bin/classes"/>\r
+</classpath>\r
diff --git a/android/examples/DirectPairing/.project b/android/examples/DirectPairing/.project
new file mode 100644 (file)
index 0000000..2dadd42
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+       <name>Iot</name>\r
+       <comment></comment>\r
+       <projects>\r
+       </projects>\r
+       <buildSpec>\r
+               <buildCommand>\r
+                       <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>org.eclipse.jdt.core.javabuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+               <buildCommand>\r
+                       <name>com.android.ide.eclipse.adt.ApkBuilder</name>\r
+                       <arguments>\r
+                       </arguments>\r
+               </buildCommand>\r
+       </buildSpec>\r
+       <natures>\r
+               <nature>com.android.ide.eclipse.adt.AndroidNature</nature>\r
+               <nature>org.eclipse.jdt.core.javanature</nature>\r
+       </natures>\r
+</projectDescription>\r
diff --git a/android/examples/DirectPairing/DirectPairing.iml b/android/examples/DirectPairing/DirectPairing.iml
new file mode 100644 (file)
index 0000000..5de258a
--- /dev/null
@@ -0,0 +1,96 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id=":DirectPairing" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="examples" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="android-gradle" name="Android-Gradle">
+      <configuration>
+        <option name="GRADLE_PROJECT_PATH" value=":DirectPairing" />
+      </configuration>
+    </facet>
+    <facet type="android" name="Android">
+      <configuration>
+        <option name="SELECTED_BUILD_VARIANT" value="debug" />
+        <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
+        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
+        <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
+        <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
+        <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
+        <afterSyncTasks>
+          <task>generateDebugAndroidTestSources</task>
+          <task>generateDebugSources</task>
+        </afterSyncTasks>
+        <option name="ALLOW_USER_CONFIGURATION" value="false" />
+        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
+        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
+        <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
+        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
+      </configuration>
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
+    <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
+    <output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
+    <exclude-output />
+    <content url="file://$MODULE_DIR$">
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
+      <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
+      <excludeFolder url="file://$MODULE_DIR$/build/reports" />
+      <excludeFolder url="file://$MODULE_DIR$/build/test-results" />
+      <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
+    </content>
+    <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-" level="project" />
+    <orderEntry type="library" exported="" name="android-android-21" level="project" />
+  </component>
+</module>
diff --git a/android/examples/DirectPairing/build.gradle b/android/examples/DirectPairing/build.gradle
new file mode 100644 (file)
index 0000000..8499e31
--- /dev/null
@@ -0,0 +1,38 @@
+apply plugin: 'com.android.application'\r
+\r
+android {\r
+    compileSdkVersion 21\r
+    buildToolsVersion "20.0.0"\r
+\r
+    defaultConfig {\r
+        applicationId "org.iotivity.base.examples.DirectPairing"\r
+        minSdkVersion 21\r
+        targetSdkVersion 21\r
+        versionCode 1\r
+        versionName "1.0"\r
+    }\r
+    buildTypes {\r
+        release {\r
+            minifyEnabled false\r
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+        }\r
+    }\r
+    lintOptions {\r
+        abortOnError false\r
+    }\r
+}\r
+repositories {\r
+    flatDir {\r
+        dirs "../../android_api/base/build/outputs/aar/"\r
+    }\r
+}\r
+\r
+try {\r
+    dependencies {\r
+        compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"\r
+    }\r
+} catch (all) {\r
+    print "${ERROR_MSG}"\r
+    assert all\r
+}\r
+\r
diff --git a/android/examples/DirectPairing/project.properties b/android/examples/DirectPairing/project.properties
new file mode 100644 (file)
index 0000000..8e02666
--- /dev/null
@@ -0,0 +1,15 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-23
+android.library.reference.1=../appcompat_v7
diff --git a/android/examples/DirectPairing/src/main/AndroidManifest.xml b/android/examples/DirectPairing/src/main/AndroidManifest.xml
new file mode 100644 (file)
index 0000000..54ec6b9
--- /dev/null
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="org.iotivity.base.examples.DirectPairing"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="19"
+        android:targetSdkVersion="21" />
+       <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+       <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
+
+    <application
+        android:allowBackup="true"
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".MainActivity"
+            android:label="@string/app_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
diff --git a/android/examples/DirectPairing/src/main/assets/oic_svr_db_client_directpairing.dat b/android/examples/DirectPairing/src/main/assets/oic_svr_db_client_directpairing.dat
new file mode 100644 (file)
index 0000000..43b7a1c
Binary files /dev/null and b/android/examples/DirectPairing/src/main/assets/oic_svr_db_client_directpairing.dat differ
diff --git a/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/ExpandableListAdapter.java b/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/ExpandableListAdapter.java
new file mode 100644 (file)
index 0000000..377917c
--- /dev/null
@@ -0,0 +1,137 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.examples.DirectPairing;
+
+import android.content.Context;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.BaseExpandableListAdapter;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+import org.iotivity.base.examples.DirectPairing.Led;
+
+import java.util.List;
+
+public class ExpandableListAdapter extends BaseExpandableListAdapter {
+    private List<String> mGroupList;
+    private List<Object> mChilditemsList;
+    private Context mContext;
+
+    public ExpandableListAdapter(List<String> groupList, List<Object> childitemsList,
+                                 Context context) {
+        super();
+        this.mContext = context;
+        this.mGroupList = groupList;
+        this.mChilditemsList = childitemsList;
+    }
+
+    @Override
+    public int getGroupCount() {
+        return mGroupList.size();
+    }
+
+    @Override
+    public int getChildrenCount(int groupPosition) {
+        return 1;
+    }
+
+    @Override
+    public Object getGroup(int groupPosition) {
+        return mGroupList.get(groupPosition);
+    }
+
+    @Override
+    public Object getChild(int groupPosition, int childPosition) {
+        return this.mChilditemsList.get(childPosition);
+    }
+
+    @Override
+    public long getGroupId(int groupPosition) {
+        return groupPosition;
+    }
+
+    @Override
+    public long getChildId(int groupPosition, int childPosition) {
+        return childPosition;
+    }
+
+    @Override
+    public boolean hasStableIds() {
+        return false;
+    }
+
+    @Override
+    public View getGroupView(int groupPosition, boolean isExpanded,
+                             View convertView, ViewGroup parent) {
+
+        String data = (String) getGroup(groupPosition);
+        if (convertView == null) {
+            LayoutInflater infalInflater = (LayoutInflater) this.mContext
+                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+            convertView = infalInflater.inflate(R.layout.list_group, null);
+        }
+
+        ImageView img = (ImageView) convertView.findViewById(R.id.image);
+        if (isExpanded) {
+            img.setImageResource(R.drawable.arrow_down);
+
+        } else {
+            img.setImageResource(R.drawable.arrow_right);
+        }
+
+        TextView groupText = (TextView) convertView.findViewById(R.id.title);
+        groupText.setText(mGroupList.get(groupPosition));
+
+        return convertView;
+    }
+
+    @Override
+    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
+                             View convertView, ViewGroup parent) {
+        LayoutInflater inflater = (LayoutInflater) mContext
+                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+        convertView = inflater.inflate(R.layout.list_item, parent, false);
+
+        Led ledResource = (Led) getChild(groupPosition, childPosition);
+        TextView textItem = (TextView) convertView
+                .findViewById(R.id.textViewItem);
+        TextView textSource = (TextView) convertView
+                .findViewById(R.id.textViewSource);
+        TextView textStatus = (TextView) convertView
+                .findViewById(R.id.textViewStatus);
+        textStatus.setText("URI:" + "/a/led");
+        textItem.setText("State: " + ledResource.getState());
+        textSource.setText("Power: " + ledResource.getPower());
+
+        return convertView;
+
+    }
+
+    @Override
+    public boolean isChildSelectable(int groupPosition, int childPosition) {
+        return true;
+    }
+
+}
diff --git a/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/Led.java b/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/Led.java
new file mode 100644 (file)
index 0000000..f44f97c
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.examples.DirectPairing;
+
+/**
+ * Led
+ * <p/>
+ * This class is used by simpleclient to create an object and update the values depending
+ * on the server response
+ */
+public class Led {
+    private boolean mState;
+    private int mPower;
+    private String mUri;
+
+    // constructor
+    public Led() {
+        mState = false;
+        mPower = 0;
+        mUri = "";
+    }
+
+    // accessor methods
+    public boolean getState() {
+        return mState;
+    }
+
+    public void setState(boolean state) {
+        mState = state;
+    }
+
+    public int getPower() {
+        return mPower;
+    }
+
+    public void setPower(int power) {
+        mPower = power;
+    }
+
+    public String getUri() {
+        return mUri;
+    }
+
+    public void setUri(String uri) {
+        mUri = uri;
+    }
+}
diff --git a/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/MainActivity.java b/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/MainActivity.java
new file mode 100644 (file)
index 0000000..90c4301
--- /dev/null
@@ -0,0 +1,534 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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.examples.DirectPairing;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.ProgressDialog;
+import android.content.DialogInterface;
+import android.content.SharedPreferences;
+import android.graphics.Color;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.os.Environment;
+import android.preference.PreferenceManager;
+import android.text.InputFilter;
+import android.util.Log;
+import android.view.View;
+import android.widget.AdapterView;
+import android.widget.AdapterView.OnItemClickListener;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CompoundButton;
+import android.widget.EditText;
+import android.widget.ExpandableListView;
+import android.widget.ExpandableListView.OnGroupExpandListener;
+import android.widget.LinearLayout;
+import android.widget.ListView;
+import android.widget.Switch;
+import android.widget.Toast;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcDirectPairDevice;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcPrmType;
+import org.iotivity.base.OcProvisioning;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+import org.iotivity.base.examples.DirectPairing.Led;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.channels.FileChannel;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+public class MainActivity extends Activity {
+    private static final int BUFFER_SIZE = 1024;
+    private static final String TAG = "DirectPairing: ";
+    private static int selected = -1;
+    private int[] pList;
+    private Button save;
+    private int prmType;
+    private EditText pinText;
+    private Led ledResource;
+    private ListView mListView;
+    private String filePath = "";
+    private OcResource led = null;
+    private Switch discoverButton;
+    private List<String> resourceInterfaces;
+    private ArrayAdapter<String> arrayAdapter;
+    private List<Object> onGetResponseList;
+    private ExpandableListAdapter exlistAdapter;
+    OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {
+        @Override
+        public synchronized void onGetCompleted(List<OcHeaderOption> headerOptionList,
+                                                OcRepresentation ocRepresentation) {
+            onGetResponseList = new ArrayList<Object>();
+            ledResource.setState(ocRepresentation.getValueBool("state"));
+            ledResource.setPower(ocRepresentation.getValueInt("power"));
+            ledResource.setUri(ocRepresentation.getUri());
+            runOnUiThread(new Runnable() {
+                public void run() {
+                    onGetResponseList.add(ledResource);
+                    exlistAdapter.notifyDataSetChanged();
+                }
+            });
+
+            Log.d(TAG, "Got a response from " + ocRepresentation.getUri() +
+                    " " + ocRepresentation.getValueBool("state") + " "
+                    + ocRepresentation.getValueInt("power") + " " +
+                    ocRepresentation.getValueString("name"));
+        }
+
+        @Override
+        public synchronized void onGetFailed(Throwable throwable) {
+            Log.d(TAG, "GET request has failed");
+            Log.e(TAG, throwable.toString());
+        }
+    };
+    private ExpandableListView mPairedListDisplay;
+    private ArrayAdapter<OcDirectPairDevice> adapter;
+    private List<String> pairedList;
+    private List<OcDirectPairDevice> discoveredListObj;
+    OcPlatform.DirectPairingListener doDPListener = new OcPlatform.DirectPairingListener() {
+        @Override
+        public void onDirectPairingListener(String devId, int result) {
+            Log.d(TAG, "Inside getDPListener");
+            if (result == StringConstants.SUCCES_CODE) {
+                pairedList.clear();
+                pairedList.add(devId);
+                onGetResponseList.add(new Led());
+                runOnUiThread(new Runnable() {
+                    public void run() {
+                        mPairedListDisplay.setAdapter(exlistAdapter);
+                        int pos = mListView.getCheckedItemPosition();
+                        if (pos != ListView.INVALID_POSITION && discoveredListObj.size() != 0) {
+                            discoveredListObj.remove(pos);
+                            adapter.notifyDataSetChanged();
+                        }
+                    }
+                });
+                Log.d(TAG, "direct pair successfull for " + devId);
+            } else {
+                Log.d(TAG, "direct pairing failed");
+                runOnUiThread(new Runnable() {
+                    public void run() {
+                        Toast.makeText(getApplicationContext(),
+                                "Direct Pairing Failed", Toast.LENGTH_SHORT).show();
+                    }
+                });
+            }
+            exportCBOR();
+        }
+    };
+    private List<OcDirectPairDevice> discoveredPairableDevices;
+    OcPlatform.FindDirectPairingListener finddirectPairing =
+            new OcPlatform.FindDirectPairingListener() {
+                @Override
+                public void onFindDirectPairingListener(List<OcDirectPairDevice> direcPairingDevice) {
+                    Log.d(TAG, "find direct pairable successfull ");
+                    discoveredListObj.clear();
+                    discoveredPairableDevices =
+                            new ArrayList<OcDirectPairDevice>(direcPairingDevice);
+                    for (int i = 0; i < direcPairingDevice.size(); i++) {
+                        OcDirectPairDevice dpPairDevice = direcPairingDevice.get(i);
+                        Log.d(TAG, "getHost from Find Direct Pairing " + dpPairDevice.getHost());
+                        discoveredListObj.add(dpPairDevice);
+                    }
+
+                    runOnUiThread(new Runnable() {
+                        public void run() {
+                            mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
+                            mListView.setAdapter(adapter);
+                            discoverButton.setChecked(false);
+                        }
+                    });
+                }
+            };
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_main);
+
+        onGetResponseList = new ArrayList<Object>();
+        discoveredListObj = new ArrayList<OcDirectPairDevice>();
+        pairedList = new ArrayList<String>();
+
+        ledResource = new Led();
+
+        mListView = (ListView) findViewById(R.id.list_view);
+        discoverButton = (Switch) findViewById(R.id.discover);
+        mPairedListDisplay = (ExpandableListView) findViewById(R.id.list_view_paired_list);
+
+
+        filePath = getFilesDir().getPath() + "/"; //  data/data/<package>/files/
+        //copy CBOR file when application runs first time
+        SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
+        boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
+        if (isFirstRun) {
+            copyCborFromAsset();
+            SharedPreferences.Editor editor = wmbPreference.edit();
+            editor.putBoolean("FIRSTRUN", false);
+            editor.commit();
+        }
+
+        initOICStack();
+
+        adapter = new ArrayAdapter<OcDirectPairDevice>(this,
+                android.R.layout.simple_list_item_single_choice,
+                discoveredListObj);
+
+        arrayAdapter = new ArrayAdapter<String>(
+                MainActivity.this,
+                android.R.layout.select_dialog_singlechoice);
+
+        save = (Button) findViewById(R.id.saveDiscovered);
+
+        save.setEnabled(false);
+        save.setBackgroundColor(Color.GRAY);
+
+        resourceInterfaces = new LinkedList<>();
+        resourceInterfaces.add(OcPlatform.DEFAULT_INTERFACE);
+
+        exlistAdapter = new ExpandableListAdapter(pairedList, onGetResponseList,
+                MainActivity.this);
+        mPairedListDisplay.setAdapter(exlistAdapter);
+
+        // to expand only a single group item.
+        mPairedListDisplay.setOnGroupExpandListener(new OnGroupExpandListener() {
+            int previousGroup = -1;
+
+            @Override
+            public void onGroupExpand(int groupPosition) {
+                Log.d(TAG, "Calling GET api on mResource");
+                try {
+                    if (null != led) led.get(new HashMap<String, String>(), onGetListener);
+                } catch (OcException e) {
+                    Log.d(TAG, "Error in GET calls");
+                    Log.e(TAG, e.getMessage());
+                }
+
+                if (groupPosition != previousGroup)
+                    mPairedListDisplay.collapseGroup(previousGroup);
+
+                previousGroup = groupPosition;
+            }
+        });
+
+        save.setOnClickListener(new View.OnClickListener() {
+
+            @Override
+            public void onClick(View v) {
+
+                AlertDialog.Builder alertPinDialog =
+                        new AlertDialog.Builder(MainActivity.this);
+                alertPinDialog.setTitle("PIN");
+                alertPinDialog.setMessage("Enter Pin");
+
+                pinText = new EditText(MainActivity.this);
+                int maxLength = 8;
+                InputFilter[] fArray = new InputFilter[1];
+                fArray[0] = new InputFilter.LengthFilter(maxLength);
+                pinText.setFilters(fArray);
+                pinText.setMaxLines(1);
+                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
+                        LinearLayout.LayoutParams.MATCH_PARENT,
+                        LinearLayout.LayoutParams.MATCH_PARENT);
+                pinText.setLayoutParams(lp);
+                alertPinDialog.setView(pinText);
+                alertPinDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
+                    public void onClick(DialogInterface dialog, int which) {
+                        selected = -1;
+                        final AlertDialog alertPrmTypeDialog = new AlertDialog.Builder
+                                (MainActivity.this)
+                                .setSingleChoiceItems(arrayAdapter, -1,
+                                        new DialogInterface.OnClickListener() {
+                                            @Override
+                                            public void onClick(DialogInterface dialog, int which) {
+                                                selected = which;
+                                                prmType = pList[which];
+                                                Log.d(TAG, " prmType " + prmType);
+                                            }
+                                        })
+                                .setTitle("Select Direct Pair Method")
+                                .setPositiveButton("OK", null)
+                                .setNegativeButton("CANCEL", null)
+                                .create();
+
+                        alertPrmTypeDialog.setOnShowListener(
+                                new DialogInterface.OnShowListener() {
+                                    @Override
+                                    public void onShow(DialogInterface dialog) {
+                                        Button ok =
+                                                alertPrmTypeDialog
+                                                        .getButton(AlertDialog.BUTTON_POSITIVE);
+
+                                        Button cancel =
+                                                alertPrmTypeDialog
+                                                        .getButton(AlertDialog.BUTTON_NEGATIVE);
+
+                                        ok.setOnClickListener(new View.OnClickListener() {
+                                            @Override
+                                            public void onClick(View view) {
+                                                int pos = mListView.getCheckedItemPosition();
+                                                if (selected == -1) {
+                                                    Toast.makeText(getApplicationContext(),
+                                                            "Please Select A Value",
+                                                            Toast.LENGTH_SHORT).show();
+                                                } else if (pos != ListView.INVALID_POSITION) {
+                                                    if (!discoveredListObj.isEmpty()) {
+                                                        try {
+                                                            OcDirectPairDevice peer =
+                                                                    (OcDirectPairDevice)
+                                                                            discoveredListObj.
+                                                                                    get(pos);
+                                                            OcPlatform.doDirectPairing(peer,
+                                                                    OcPrmType.convertOcPrmType(prmType),
+                                                                    pinText.getText().toString(),
+                                                                    doDPListener);
+                                                        } catch (OcException e) {
+                                                            Log.d(TAG, "do Direct Pairing error: "
+                                                                    + e.getMessage());
+                                                            Log.e(TAG, e.getMessage());
+                                                        }
+
+                                                        alertPrmTypeDialog.dismiss();
+                                                    } else {
+                                                        alertPrmTypeDialog.dismiss();
+                                                    }
+                                                }
+                                            }
+                                        });
+
+                                        cancel.setOnClickListener(new View.OnClickListener() {
+                                            @Override
+                                            public void onClick(View view) {
+                                                alertPrmTypeDialog.dismiss();
+                                            }
+                                        });
+                                    }
+                                });
+
+                        alertPrmTypeDialog.show();
+                    }
+                });
+                alertPinDialog.show();
+            }
+        });
+
+        mListView.setOnItemClickListener(new OnItemClickListener() {
+            @Override
+            public void onItemClick(AdapterView adapt, View view, int position, long itemId) {
+                save.setEnabled(true);
+                save.setBackgroundColor(Color.parseColor("#13AEF4"));
+                OcDirectPairDevice dpPairDevice =
+                        (OcDirectPairDevice) adapt.getItemAtPosition(position);
+                Log.d(TAG, "DevId On List Item Clicked " + dpPairDevice.getDevId());
+                List<Integer> pTypeList = dpPairDevice.getPairingMethodList();
+                pList = new int[pTypeList.size()];
+                       Iterator<Integer> iterator = pTypeList.iterator();
+                       for(int k = 0; k < pList.length; k++){
+                           pList[k]=iterator.next().intValue();
+                       }
+                arrayAdapter.clear();
+                for (int j = 0; j < pList.length; j++) {
+                    Log.d(TAG, " List Item Value " + pList[j]);
+                    OcPrmType prmTy = OcPrmType.convertOcPrmType(pList[j]);
+                    arrayAdapter.add(prmTy.name());
+                }
+            }
+        });
+
+        discoverButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+                if (isChecked) {
+                    save.setEnabled(false);
+                    save.setBackgroundColor(Color.GRAY);
+                    new GetDiscoveredItems().execute();
+                }
+            }
+        });
+
+    }
+
+    /**
+     * Copy svr db CBOR dat file from assets folder to app data files dir
+     */
+    private void copyCborFromAsset() {
+        InputStream inputStream = null;
+        OutputStream outputStream = null;
+        int length;
+        byte[] buffer = new byte[BUFFER_SIZE];
+        try {
+            inputStream = getAssets().open(StringConstants.OIC_CLIENT_CBOR_DB_FILE);
+            File file = new File(filePath);
+            //check files directory exists
+            if (!(file.exists() && file.isDirectory())) {
+                file.mkdirs();
+            }
+            outputStream = new FileOutputStream(filePath +
+                    StringConstants.OIC_CLIENT_CBOR_DB_FILE);
+            while ((length = inputStream.read(buffer)) != -1) {
+                outputStream.write(buffer, 0, length);
+            }
+        } catch (NullPointerException e) {
+            Log.d(TAG, "Null pointer exception " + e.getMessage());
+            Log.e(TAG, e.getMessage());
+        } catch (FileNotFoundException e) {
+            Log.d(TAG, "CBOR svr db file not found " + e.getMessage());
+            Log.e(TAG, e.getMessage());
+        } catch (IOException e) {
+            Log.d(TAG, StringConstants.OIC_CLIENT_CBOR_DB_FILE + " file copy failed");
+            Log.e(TAG, e.getMessage());
+        } finally {
+            if (inputStream != null) {
+                try {
+                    inputStream.close();
+                } catch (IOException e) {
+                    Log.e(TAG, e.getMessage());
+                }
+            }
+            if (outputStream != null) {
+                try {
+                    outputStream.close();
+                } catch (IOException e) {
+                    Log.e(TAG, e.getMessage());
+                }
+            }
+        }
+    }
+
+    void exportCBOR() {
+        try {
+            File sd = Environment.getExternalStorageDirectory();
+            File data = Environment.getDataDirectory();
+            if (sd.canWrite()) {
+                String currentDBPath = "/data/data/" + getPackageName() +
+                        "/files/" + StringConstants.OIC_CLIENT_CBOR_DB_FILE;
+                File currentDB = new File(currentDBPath);
+                File backupDB = new File(sd, StringConstants.OIC_CLIENT_CBOR_DB_FILE);
+                if (currentDB.exists()) {
+                    FileChannel src = new FileInputStream(currentDB).getChannel();
+                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
+                    dst.transferFrom(src, 0, src.size());
+                    src.close();
+                    dst.close();
+                }
+            }
+        } catch (Exception e) {
+            Log.e(TAG, e.getMessage());
+        }
+    }
+
+    /**
+     * configure OIC platform and call findResource
+     */
+    private void initOICStack() {
+        //create platform config
+        PlatformConfig cfg = new PlatformConfig(this, ServiceType.IN_PROC, ModeType.CLIENT_SERVER,
+                "0.0.0.0", // bind to all available interfaces
+                0,
+                QualityOfService.LOW, filePath + StringConstants.OIC_CLIENT_CBOR_DB_FILE);
+        OcPlatform.Configure(cfg);
+        try {
+            /*
+             * Initialize DataBase
+             */
+            String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
+                    File.separator;
+            File file = new File(sqlDbPath);
+            //check files directory exists
+            if (!(file.isDirectory())) {
+                file.mkdirs();
+                Log.d(TAG, "Sql db directory created at " + sqlDbPath);
+            }
+            Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
+            OcProvisioning.provisionInit(sqlDbPath + StringConstants.OIC_SQL_DB_FILE);
+        } catch (OcException e) {
+            Log.d(TAG, "provisionInit error: " + e.getMessage());
+            Log.e(TAG, e.getMessage());
+        }
+    }
+
+    class GetDiscoveredItems extends AsyncTask<Void, Void, List<String>> {
+
+        ProgressDialog pDialog;
+
+        @Override
+        protected void onPreExecute() {
+            pDialog = new ProgressDialog(MainActivity.this);
+            pDialog.setMessage("Getting Discovered Items");
+            pDialog.setCancelable(false);
+            pDialog.setCanceledOnTouchOutside(false);
+            pDialog.show();
+        }
+
+        ;
+
+        @Override
+        protected List<String> doInBackground(Void... params) {
+            try {
+                OcPlatform.findDirectPairingDevices(5, finddirectPairing);
+            } catch (OcException e) {
+                Log.e(TAG, e.getMessage());
+            }
+            return null;
+        }
+
+        @Override
+        protected void onPostExecute(List<String> discoveredItems) {
+            pDialog.dismiss();
+            for (Iterator iterator = discoveredListObj.iterator(); iterator.hasNext(); ) {
+                OcDirectPairDevice ledResource = (OcDirectPairDevice) iterator.next();
+                List<String> lightTypes = new LinkedList<>();
+                lightTypes.add("core.led");
+                try {
+                    Log.d(TAG, "Constructing Led Resource");
+                    led = OcPlatform.constructResourceObject(ledResource.getHost(),
+                            "/a/led", ledResource.getConnectivityTypeSet(),
+                            false, //isObservable
+                            lightTypes,
+                            resourceInterfaces);
+                    Log.d(TAG, "Constructed Led Resource");
+                } catch (OcException e) {
+                    Log.e(TAG, e.getMessage());
+                }
+            }
+        }
+
+    }
+}
diff --git a/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/StringConstants.java b/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/StringConstants.java
new file mode 100644 (file)
index 0000000..c793422
--- /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.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.base.examples.DirectPairing;
+
+public interface StringConstants {
+
+    public static final int NUMBER_ZERO = 0;
+    public static final int DISCOVERY_TIMEOUT_10 = 10;
+    public static final int DISCOVERY_TIMEOUT_20 = 20;
+    public static final int SUCCES_CODE = 0;
+    public static final String DEFAULT_ROWNER_ID = "61646d69-6e44-6576-6963-655555494430";
+    public static final String DEFAULT_RESOURCES = "*";
+    public static final String DEFAULT_RECURRENCES = "Daily";
+    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_directpairing.dat";
+    public static final String MESSAGE = "message";
+    public static final String OIC_SQL_DB_FILE = "Pdm.db";
+    public static final int CREDENTIAL_TYPE = 1;
+    public static final int OWNER_PSK_LENGTH_128 = 128 / 8;
+}
diff --git a/android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_down.png b/android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_down.png
new file mode 100644 (file)
index 0000000..2e69816
Binary files /dev/null and b/android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_down.png differ
diff --git a/android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_right.png b/android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_right.png
new file mode 100644 (file)
index 0000000..91667d5
Binary files /dev/null and b/android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_right.png differ
diff --git a/android/examples/DirectPairing/src/main/res/drawable-hdpi/ic_launcher.png b/android/examples/DirectPairing/src/main/res/drawable-hdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..288b665
Binary files /dev/null and b/android/examples/DirectPairing/src/main/res/drawable-hdpi/ic_launcher.png differ
diff --git a/android/examples/DirectPairing/src/main/res/drawable-mdpi/ic_launcher.png b/android/examples/DirectPairing/src/main/res/drawable-mdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..6ae570b
Binary files /dev/null and b/android/examples/DirectPairing/src/main/res/drawable-mdpi/ic_launcher.png differ
diff --git a/android/examples/DirectPairing/src/main/res/drawable-xhdpi/ic_launcher.png b/android/examples/DirectPairing/src/main/res/drawable-xhdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..d4fb7cd
Binary files /dev/null and b/android/examples/DirectPairing/src/main/res/drawable-xhdpi/ic_launcher.png differ
diff --git a/android/examples/DirectPairing/src/main/res/drawable-xxhdpi/ic_launcher.png b/android/examples/DirectPairing/src/main/res/drawable-xxhdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..85a6081
Binary files /dev/null and b/android/examples/DirectPairing/src/main/res/drawable-xxhdpi/ic_launcher.png differ
diff --git a/android/examples/DirectPairing/src/main/res/layout/activity_main.xml b/android/examples/DirectPairing/src/main/res/layout/activity_main.xml
new file mode 100644 (file)
index 0000000..1ee1a2b
--- /dev/null
@@ -0,0 +1,95 @@
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+    xmlns:tools="http://schemas.android.com/tools"\r
+    android:layout_width="match_parent"\r
+    android:layout_height="match_parent"\r
+    android:orientation="vertical"\r
+    android:paddingBottom="@dimen/activity_vertical_margin"\r
+    android:paddingLeft="@dimen/activity_horizontal_margin"\r
+    android:paddingRight="@dimen/activity_horizontal_margin"\r
+    android:paddingTop="@dimen/activity_vertical_margin"\r
+    tools:context="com.example.iot.MainActivity" >\r
+\r
+    <LinearLayout\r
+        android:layout_width="match_parent"\r
+        android:layout_height="wrap_content"\r
+        android:weightSum="1" >\r
+\r
+        <TextView\r
+            android:layout_width="wrap_content"\r
+            android:layout_height="wrap_content"\r
+            android:layout_weight="0.75"\r
+            android:gravity="center"\r
+            android:text="@string/discover_items"\r
+            android:textSize="18sp" />\r
+\r
+        <Switch\r
+            android:id="@+id/discover"\r
+            android:layout_width="wrap_content"\r
+            android:layout_height="wrap_content"\r
+            android:layout_weight="0.25" />\r
+    </LinearLayout>\r
+\r
+    <View\r
+        android:layout_width="match_parent"\r
+        android:layout_height="2dp"\r
+        android:background="#13AEF4" />\r
+\r
+    <ListView\r
+        android:id="@+id/list_view"\r
+        android:layout_width="match_parent"\r
+        android:layout_height="250dp" />\r
+\r
+    <View\r
+        android:layout_width="match_parent"\r
+        android:layout_height="2dp"\r
+        android:background="#13AEF4" />\r
+\r
+    <RelativeLayout\r
+        android:id="@+id/relLay"\r
+        android:layout_width="fill_parent"\r
+        android:layout_height="wrap_content"\r
+        android:orientation="horizontal"\r
+        android:padding="15dp" >\r
+\r
+        <Button\r
+            android:id="@+id/saveDiscovered"\r
+            android:layout_width="90dp"\r
+            android:layout_height="30dp"\r
+            android:layout_centerInParent="true"\r
+            android:background="#13AEF4"\r
+            android:text="Save"\r
+            android:textColor="#FFFFFF" />\r
+    </RelativeLayout>\r
+\r
+    <View\r
+        android:layout_width="match_parent"\r
+        android:layout_height="2dp"\r
+        android:background="#13AEF4" />\r
+\r
+    <TextView\r
+        android:layout_width="match_parent"\r
+        android:layout_height="wrap_content"\r
+        android:layout_gravity="center_vertical"\r
+        android:paddingLeft="50dp"\r
+        android:text="@string/paired_list"\r
+        android:textSize="18sp" />\r
+\r
+    <View\r
+        android:layout_width="match_parent"\r
+        android:layout_height="2dp"\r
+        android:background="#13AEF4" />\r
+\r
+    <ExpandableListView\r
+        android:id="@+id/list_view_paired_list"\r
+        android:layout_width="fill_parent"\r
+        android:layout_height="200dp"\r
+        android:paddingTop="5dp"\r
+        android:groupIndicator="@null" >\r
+    </ExpandableListView>\r
+\r
+    <View\r
+        android:layout_width="match_parent"\r
+        android:layout_height="2dp"\r
+        android:background="#13AEF4" />\r
+\r
+</LinearLayout>
\ No newline at end of file
diff --git a/android/examples/DirectPairing/src/main/res/layout/custom_list_view.xml b/android/examples/DirectPairing/src/main/res/layout/custom_list_view.xml
new file mode 100644 (file)
index 0000000..74874c5
--- /dev/null
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="fill_parent"
+    android:layout_height="wrap_content"
+    android:orientation="horizontal"
+    android:padding="10dp" >
+
+    <TextView
+        android:id="@+id/textView"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="Discovered Items"
+        android:layout_centerVertical="true"
+         android:layout_gravity="center_vertical"
+        android:textColor="#545454"
+        android:textSize="15sp" />
+
+    <LinearLayout
+         android:id="@+id/linearLay"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentRight="true"
+        android:layout_centerVertical="true" >
+
+        <CheckBox
+            android:id="@+id/checkBox"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_centerVertical="true"
+            android:layout_gravity="center_vertical"
+            android:layout_marginRight="10dp" />
+    </LinearLayout>
+
+</RelativeLayout>
\ No newline at end of file
diff --git a/android/examples/DirectPairing/src/main/res/layout/group_indicator.xml b/android/examples/DirectPairing/src/main/res/layout/group_indicator.xml
new file mode 100644 (file)
index 0000000..95be916
--- /dev/null
@@ -0,0 +1,6 @@
+<selector xmlns:android="http://schemas.android.com/apk/res/android">\r
+         <item android:drawable="@drawable/arrow_right" android:state_empty="true"></item>\r
+            <item android:drawable="@drawable/arrow_down" android:state_expanded="true"></item>\r
+            <item android:drawable="@drawable/arrow_right"></item>\r
+\r
+</selector>
\ No newline at end of file
diff --git a/android/examples/DirectPairing/src/main/res/layout/list_group.xml b/android/examples/DirectPairing/src/main/res/layout/list_group.xml
new file mode 100644 (file)
index 0000000..d4d9218
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+    android:layout_width="fill_parent"\r
+    android:layout_height="40dp"\r
+    android:background="#ffffff"\r
+    android:orientation="horizontal" >\r
+\r
+    <TextView\r
+        android:id="@+id/title"\r
+        android:layout_width="wrap_content"\r
+        android:layout_height="40dp"\r
+        android:layout_weight="0.9"\r
+        android:gravity="center_vertical"\r
+        android:paddingLeft="40dp"\r
+        android:text="Items"\r
+        android:textColor="#040404"\r
+        android:textSize="16sp"\r
+        android:textStyle="bold"\r
+        android:typeface="sans" />\r
+\r
+    <ImageView\r
+        android:id="@+id/image"\r
+        android:layout_width="wrap_content"\r
+        android:layout_height="20dp"\r
+        android:layout_gravity="center_vertical"\r
+        android:layout_weight="0.1" />\r
+\r
+</LinearLayout>
\ No newline at end of file
diff --git a/android/examples/DirectPairing/src/main/res/layout/list_item.xml b/android/examples/DirectPairing/src/main/res/layout/list_item.xml
new file mode 100644 (file)
index 0000000..6579c36
--- /dev/null
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+    android:layout_width="fill_parent"\r
+    android:layout_height="wrap_content"\r
+    android:orientation="vertical" >\r
+\r
+    <TextView\r
+        android:id="@+id/textViewItem"\r
+        android:layout_width="wrap_content"\r
+        android:layout_height="wrap_content"\r
+        android:gravity="center_vertical"\r
+        android:paddingLeft="50dp"\r
+        android:text="Paired Items"\r
+        android:textColor="#545454"\r
+        android:textSize="15sp" />\r
+\r
+    <TextView\r
+        android:id="@+id/textViewSource"\r
+        android:layout_below="@id/textViewItem"\r
+        android:layout_width="wrap_content"\r
+        android:layout_height="wrap_content"\r
+        android:gravity="center_vertical"\r
+        android:paddingLeft="50dp"\r
+        android:text="Paired Source"\r
+        android:textColor="#545454"\r
+        android:textSize="15sp" />\r
+\r
+    <TextView\r
+        android:id="@+id/textViewStatus"\r
+        android:layout_below="@id/textViewSource"\r
+        android:layout_width="wrap_content"\r
+        android:layout_height="wrap_content"\r
+        android:gravity="center_vertical"\r
+        android:paddingLeft="50dp"\r
+        android:text="Paired Status"\r
+        android:textColor="#545454"\r
+        android:textSize="15sp" />\r
+\r
+</RelativeLayout>
\ No newline at end of file
diff --git a/android/examples/DirectPairing/src/main/res/menu/main.xml b/android/examples/DirectPairing/src/main/res/menu/main.xml
new file mode 100644 (file)
index 0000000..3e5155b
--- /dev/null
@@ -0,0 +1,11 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android"\r
+    xmlns:app="http://schemas.android.com/apk/res-auto"\r
+    xmlns:tools="http://schemas.android.com/tools"\r
+    tools:context="org.iotivity.base.examples.MainActivity" >\r
+\r
+    <item\r
+        android:id="@+id/action_settings"\r
+        android:orderInCategory="100"\r
+        android:title="@string/action_settings"/>\r
+\r
+</menu>\r
diff --git a/android/examples/DirectPairing/src/main/res/values-v11/styles.xml b/android/examples/DirectPairing/src/main/res/values-v11/styles.xml
new file mode 100644 (file)
index 0000000..0ce1396
--- /dev/null
@@ -0,0 +1,11 @@
+<resources>\r
+\r
+    <!--\r
+        Base application theme for API 11+. This theme completely replaces
+        AppBaseTheme from res/values/styles.xml on API 11+ devices.\r
+    -->\r
+    <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">\r
+        <!-- API 11 theme customizations can go here. -->\r
+    </style>\r
+\r
+</resources>\r
diff --git a/android/examples/DirectPairing/src/main/res/values-v14/styles.xml b/android/examples/DirectPairing/src/main/res/values-v14/styles.xml
new file mode 100644 (file)
index 0000000..94dd245
--- /dev/null
@@ -0,0 +1,12 @@
+<resources>\r
+\r
+    <!--\r
+        Base application theme for API 14+. This theme completely replaces
+        AppBaseTheme from BOTH res/values/styles.xml and
+        res/values-v11/styles.xml on API 14+ devices.\r
+    -->\r
+    <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">\r
+        <!-- API 14 theme customizations can go here. -->\r
+    </style>\r
+\r
+</resources>\r
diff --git a/android/examples/DirectPairing/src/main/res/values-w820dp/dimens.xml b/android/examples/DirectPairing/src/main/res/values-w820dp/dimens.xml
new file mode 100644 (file)
index 0000000..f9f069f
--- /dev/null
@@ -0,0 +1,10 @@
+<resources>\r
+\r
+    <!--\r
+         Example customization of dimensions originally defined in res/values/dimens.xml
+         (such as screen margins) for screens with more than 820dp of available width. This
+         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).\r
+    -->\r
+    <dimen name="activity_horizontal_margin">64dp</dimen>\r
+\r
+</resources>\r
diff --git a/android/examples/DirectPairing/src/main/res/values/dimens.xml b/android/examples/DirectPairing/src/main/res/values/dimens.xml
new file mode 100644 (file)
index 0000000..2e0e2ae
--- /dev/null
@@ -0,0 +1,7 @@
+<resources>\r
+\r
+    <!-- Default screen margins, per the Android Design guidelines. -->\r
+    <dimen name="activity_horizontal_margin">16dp</dimen>\r
+    <dimen name="activity_vertical_margin">16dp</dimen>\r
+\r
+</resources>\r
diff --git a/android/examples/DirectPairing/src/main/res/values/strings.xml b/android/examples/DirectPairing/src/main/res/values/strings.xml
new file mode 100644 (file)
index 0000000..0fe7671
--- /dev/null
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>\r
+\r
+    <string name="app_name">DirectPairingClient</string>\r
+    <string name="discover_items">Discover Resources</string>
+    <string name="paired_items">Paired Resources</string>
+    <string name="paired_list">Direct Paired Resources</string>\r
+    <string name="action_settings">Settings</string>\r
+\r
+</resources>\r
diff --git a/android/examples/DirectPairing/src/main/res/values/styles.xml b/android/examples/DirectPairing/src/main/res/values/styles.xml
new file mode 100644 (file)
index 0000000..287aa96
--- /dev/null
@@ -0,0 +1,20 @@
+<resources>\r
+\r
+    <!--\r
+        Base application theme, dependent on API level. This theme is replaced
+        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.\r
+    -->\r
+    <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">\r
+        <!--\r
+            Theme customizations available in newer API levels can go in
+            res/values-vXX/styles.xml, while customizations related to
+            backward-compatibility can go here.\r
+        -->\r
+    </style>\r
+\r
+    <!-- Application theme. -->\r
+    <style name="AppTheme" parent="AppBaseTheme">\r
+        <!-- All customizations that are NOT specific to a particular API-level can go here. -->\r
+    </style>\r
+\r
+</resources>\r
index 6c2d317..28f9a93 100644 (file)
@@ -127,7 +127,7 @@ public class DeviceDiscoveryClient extends Activity implements
     private final static Map<String, String> DEVICE_INFO_KEYS = new HashMap<String, String>() {{
         put("di", "Device ID: ");
         put("n", "Device name: ");
-        put("lcv", "Spec version url: ");
+        put("icv", "Spec version url: ");
         put("dmv", "Data Model: ");
     }};
 
@@ -138,6 +138,12 @@ public class DeviceDiscoveryClient extends Activity implements
             for (String key : DEVICE_INFO_KEYS.keySet()) {
                 msg("\t" + DEVICE_INFO_KEYS.get(key) + ocRepresentation.getValue(key));
             }
+
+            msg("\tDevice types:");
+
+            for (String type : ocRepresentation.getResourceTypes()) {
+                msg("\t\t" + type);
+            }
         } catch (OcException e) {
             Log.e(TAG, e.toString());
             msg("Failed to read device info values.");
index a2920f4..c0d96b7 100644 (file)
@@ -40,6 +40,8 @@ import org.iotivity.base.PlatformConfig;
 import org.iotivity.base.QualityOfService;
 import org.iotivity.base.ServiceType;
 
+import java.util.Arrays;
+
 /**
  * This sample demonstrates platform and device discovery feature.
  * The server sets the platform and device related info. which can be later retrieved by a client.
@@ -61,7 +63,11 @@ public class DeviceDiscoveryServer extends Activity {
         msg("Configuring platform.");
         OcPlatform.Configure(platformConfig);
 
-        OcDeviceInfo deviceInfo = new OcDeviceInfo("myDeviceName");
+        OcDeviceInfo deviceInfo = new OcDeviceInfo(
+                "myDeviceName",
+                Arrays.asList(new String[]{"oic.d.phone"})
+        );
+
         try {
             msg("Registering device info");
             OcPlatform.registerDeviceInfo(deviceInfo);
index b8d249c..d498faa 100644 (file)
Binary files a/android/examples/provisioningclient/src/main/assets/oic_svr_db_client.dat and b/android/examples/provisioningclient/src/main/assets/oic_svr_db_client.dat differ
index 22dfeba..9371a3c 100644 (file)
@@ -8,38 +8,32 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
                         },\r
                         {\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/ad",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.ad"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/amacl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.amacl"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        }                  \r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
+                        }\r
                     ],\r
                     "permission": 2\r
                 }\r
             ]\r
         },\r
         "rowneruuid" : "61646D69-6E44-6576-6963-655575696430"\r
-    },    \r
+    },\r
     "pstat": {\r
         "isop": true,\r
         "cm": 2,\r
@@ -81,7 +75,7 @@
         "sct": 1,\r
         "owned": true,\r
         "deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
-        "dpc": false,\r
+        "x.com.samsung.dpc": false,\r
         "devowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
         "rowneruuid": "61646D69-6E44-6576-6963-655575696430"\r
     }\r
index fbd8eda..db828b5 100644 (file)
@@ -24,6 +24,8 @@ import org.iotivity.base.OcPlatform;
 import org.iotivity.base.OcProvisioning;
 import org.iotivity.base.OcSecureResource;
 import org.iotivity.base.OicSecAcl;
+import org.iotivity.base.OicSecPdAcl;
+import org.iotivity.base.OcPrmType;
 import org.iotivity.base.OxmType;
 import org.iotivity.base.PlatformConfig;
 import org.iotivity.base.ProvisionResult;
@@ -59,6 +61,22 @@ public class ProvisioningClient extends Activity implements
     private List<OcSecureResource> deviceList;
     private List<OcSecureResource> ownedDeviceList;
     private TextView mEventsTextView;
+
+    OcSecureResource.ProvisionDirectPairingListener provisionDPListener =
+            new OcSecureResource.ProvisionDirectPairingListener() {
+                @Override
+                public void provisionDirectPairingListener(List<ProvisionResult> provisionResults,
+                                                           int hasError) {
+                    Log.d(TAG, "Inside provisionDPListener");
+                    ProvisionResult pResult = provisionResults.get(0);
+                    if (hasError == StringConstants.ERROR_CODE) {
+                        logMessage(TAG + "Provision direct pairing Failed for " + pResult.getDevId());
+                    } else {
+                        logMessage(TAG + "Provision direct pairing Successful for " + pResult.getDevId());
+                    }
+                }
+            };
+
     OcSecureResource.ProvisionAclListener provisionAclListener =
             new OcSecureResource.ProvisionAclListener() {
                 @Override
@@ -123,7 +141,7 @@ public class ProvisioningClient extends Activity implements
         mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
         LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
         layout.addView(mEventsTextView, new LinearLayout.LayoutParams(
-                        LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+                LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
         );
         filePath = getFilesDir().getPath() + "/"; //  data/data/<package>/files/
         //copy CBOR file when application runs first time
@@ -188,6 +206,32 @@ public class ProvisioningClient extends Activity implements
         }
     }
 
+
+    private void doDPProvisioning() {
+        try {
+            logMessage(TAG + "Provision direct pairing for " + ownedDeviceList.get(0).getDeviceID());
+            newSecureResource = ownedDeviceList.get(0);
+            String pin = "00000000";
+            List<OcPrmType>prmTypes = new ArrayList<OcPrmType>();
+            prmTypes.add(OcPrmType.DP_PRE_CONFIGURED);
+            boolean edp = true;
+            List<String> resources = new ArrayList<String>();
+            List<String> periods = new ArrayList<String>();
+            List<String> recurrences = new ArrayList<String>();
+            resources.add(StringConstants.DEFAULT_RESOURCES);
+            OicSecPdAcl pdAcl = new OicSecPdAcl(recurrences, periods,
+                    StringConstants.DEFAULT_PERMISSION, resources);
+            OicSecPdAcl[] oicSecPdAcls = new OicSecPdAcl[1];
+            oicSecPdAcls[0] = pdAcl;
+            newSecureResource.doProvisionDirectPairing(pin, oicSecPdAcls, prmTypes, edp,
+                    provisionDPListener);
+        } catch (Exception e) {
+            logMessage(TAG + "Direct Pairing Provisioning error: " + e.getMessage());
+            Log.e(TAG, e.getMessage());
+        }
+    }
+
+
     private void doPairwiseProvisioning() {
         try {
             logMessage(TAG + "Pairwise Provisioning b/w " + ownedDeviceList.get(0).getDeviceID()
@@ -544,11 +588,11 @@ public class ProvisioningClient extends Activity implements
                 if (ownedDeviceList.size() > 0) {
                     for (int i = 0; i < ownedDeviceList.size(); i++) {
                         publishProgress(TAG + "Owned Discovered Device " + (i + 1) + "= " +
-                                        ownedDeviceList.get(i).getDeviceID()
-                                        + "\nIP Address= " + ownedDeviceList.get(i).getIpAddr()
-                                        + "\nOwned Status= " + ownedDeviceList.get(i).getOwnedStatus()
-                                        + "\nDevice Status= " + ((ownedDeviceList.get(i).
-                                        getDeviceStatus() == DeviceStatus.ON) ? "ON" : "OFF")
+                                ownedDeviceList.get(i).getDeviceID()
+                                + "\nIP Address= " + ownedDeviceList.get(i).getIpAddr()
+                                + "\nOwned Status= " + ownedDeviceList.get(i).getOwnedStatus()
+                                + "\nDevice Status= " + ((ownedDeviceList.get(i).
+                                getDeviceStatus() == DeviceStatus.ON) ? "ON" : "OFF")
                         );
                     }
                 } else {
@@ -568,6 +612,12 @@ public class ProvisioningClient extends Activity implements
 
         @Override
         protected void onPostExecute(String s) {
+
+
+            if (ownedDeviceList.size() > 0 && "success".equals(s)) {
+                doDPProvisioning();
+            }
+
             if (ownedDeviceList.size() > 1 && "success".equals(s)) {
                 doPairwiseProvisioning();
             }
index cde94ab..3d6612a 100755 (executable)
@@ -1,5 +1,5 @@
 include ':simpleserver', ':simpleclient', ':fridgeserver', ':fridgeclient', ':guiclient', ':presenceserver', ':presenceclient', ':devicediscoveryclient', ':devicediscoveryserver', ':groupclient', ':groupserver', ':fridgegroupclient', ':fridgegroupserver', ':simplebase'
 SECURED=System.getProperty('SECURE')
 if(SECURED== "1"){
-        include ':provisioningclient'
+        include ':provisioningclient', ':DirectPairing'
 }
index 9de47b8..983affd 100644 (file)
Binary files a/android/examples/simpleclient/src/main/assets/oic_svr_db_client.dat and b/android/examples/simpleclient/src/main/assets/oic_svr_db_client.dat differ
index 5052bd1..f3840be 100644 (file)
@@ -8,38 +8,32 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
                         },\r
                         {\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/ad",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.ad"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
-                            "href": "/oic/sec/acl",\r
+                            "href": "/oic/sec/amacl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.amacl"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        } ,\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
@@ -83,7 +77,7 @@
         "deviceuuid": "32323232-3232-3232-3232-323232323232",\r
         "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
         "rowneruuid": "32323232-3232-3232-3232-323232323232",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     },\r
     "cred": {\r
         "creds": [\r
index 31e1814..742069a 100644 (file)
Binary files a/android/examples/simpleserver/src/main/assets/oic_svr_db_server.dat and b/android/examples/simpleserver/src/main/assets/oic_svr_db_server.dat differ
index 0e1bf23..6094a95 100644 (file)
@@ -8,38 +8,32 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
                         },\r
                         {\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/ad",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.ad"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        } ,\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/a/light",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.core"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/a/light0",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.core"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/a/light1",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.core"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 6\r
         "deviceuuid": "31313131-3131-3131-3131-313131313131",\r
         "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
         "rowneruuid": "31313131-3131-3131-3131-313131313131",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     },\r
     "cred": {\r
         "creds": [\r
index 2be70ce..ad3617e 100644 (file)
@@ -8,17 +8,18 @@ import platform
 # Map of host os and allowed target os (host: allowed target os)
 host_target_map = {
                'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
-               'windows': ['windows', 'winrt', 'android', 'arduino'],
+               'windows': ['windows', 'android', 'arduino'],
                'darwin': ['darwin', 'ios', 'android', 'arduino'],
+               'msys_nt' :['msys_nt'],
                }
 
 # Map of os and allowed archs (os: allowed archs)
 os_arch_map = {
-               'linux': ['x86', 'x86_64', 'arm', 'arm64'],
-               'tizen': ['x86', 'x86_64', 'arm', 'arm64', 'armeabi-v7a'],
+               'linux': ['x86', 'x86_64', 'arm', 'arm-v7a', 'arm64'],
+               'tizen': ['x86', 'x86_64', 'arm', 'arm-v7a', 'armeabi-v7a', 'arm64'],
                'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
                'windows': ['x86', 'amd64', 'arm'],
-               'winrt': ['arm'],
+               'msys_nt':['x86', 'x86_64'],
                'darwin': ['i386', 'x86_64'],
                'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
                'arduino': ['avr', 'arm'],
@@ -27,6 +28,11 @@ os_arch_map = {
 
 host = platform.system().lower()
 
+# the host string contains version of windows. 6.3, 6.4, 10.0 which is 8.0, 8.1, and 10 respectively.
+# Let's canonicalize the msys_nt-XX.X system name  by stripping version off.
+if 'msys_nt' in host:
+       host = 'msys_nt'
+
 if not host_target_map.has_key(host):
        print "\nError: Current system (%s) isn't supported\n" % host
        Exit(1)
@@ -180,6 +186,14 @@ if target_os in targets_support_cc:
        if prefix or tc_path:
                print tc_set_msg
 
+# If cross-compiling, honor environment settings for toolchain to avoid picking up native tools
+if os.environ.get('PKG_CONFIG') != None:
+       env["ENV"]["PKG_CONFIG"] = os.environ.get("PKG_CONFIG")
+if os.environ.get('PKG_CONFIG_PATH') != None:
+       env["ENV"]["PKG_CONFIG_PATH"] = os.environ.get("PKG_CONFIG_PATH")
+if os.environ.get('PKG_CONFIG_SYSROOT_DIR') != None:
+       env["ENV"]["PKG_CONFIG_SYSROOT_DIR"] = os.environ.get("PKG_CONFIG_SYSROOT_DIR")
+
 # Ensure scons be able to change its working directory
 env.SConscriptChdir(1)
 
@@ -230,6 +244,9 @@ def __installlib(ienv, targets, name):
                else:
                        i_n = ienv.Install(user_prefix + '/lib', targets)
                ienv.Alias("install", i_n)
+       else:
+               i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+       ienv.Alias("install", i_n)
 
 def __installbin(ienv, targets, name):
        user_prefix = env.get('PREFIX')
@@ -241,7 +258,9 @@ def __installheader(ienv, targets, dir, name):
        user_prefix = env.get('PREFIX')
        if user_prefix:
                i_n = ienv.Install(user_prefix + '/include/' + dir ,targets)
-               ienv.Alias("install", i_n)
+       else:
+               i_n = ienv.Install(os.path.join(env.get('BUILD_DIR'), 'include', dir), targets)
+       ienv.Alias("install", i_n)
 
 def __installpcfile(ienv, targets, name):
        user_prefix = env.get('PREFIX')
@@ -251,7 +270,9 @@ def __installpcfile(ienv, targets, name):
                        i_n = ienv.Install(user_lib + '/pkgconfig', targets)
                else:
                        i_n = ienv.Install(user_prefix + '/lib/pkgconfig', targets)
-               ienv.Alias("install", i_n)
+       else:
+               i_n = ienv.Install(env.get('BUILD_DIR') + 'lib/pkgconfig', targets)
+       ienv.Alias("install", i_n)
 
 def __append_target(ienv, name, targets = None):
        if targets:
@@ -303,14 +324,14 @@ if not user_lib:
 if user_prefix:
        pc_vars = {'\@PREFIX\@': user_prefix,
                                '\@EXEC_PREFIX\@':user_prefix,
-                               '\@VERSION\@': '1.0.1',
+                               '\@VERSION\@': '1.1.1',
                                '\@LIB_INSTALL_DIR\@': user_lib,
                                '\@ROUTING_DEFINE\@': routing_define
                                }
 else:
-       pc_vars = {'\@PREFIX\@': env.get('BUILD_DIR'),
-                               '\@EXEC_PREFIX\@': env.get('BUILD_DIR'),
-                               '\@VERSION\@': '1.0.1',
+       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
                                }
@@ -413,6 +434,52 @@ 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 73e753e..5dffa92 100644 (file)
@@ -259,6 +259,9 @@ if env.get('RELEASE'):
 else:
        env.AppendUnique(CCFLAGS = ['-g'])
 
+# Force header presence defines
+env.AppendUnique(CPPDEFINES = ['HAVE_ARDUINO_TIME_H'])
+
 # BOARD / CPU option
 
 # Get IDE version
index 2e28220..f1e8295 100644 (file)
@@ -40,8 +40,9 @@ if target_os == 'darwin':
 
 # External library include files are in <src_dir>/deps/<target_os>/include
 # the library binaries are in <src_dir>/deps/<target_os>/lib/<arch>
-env.AppendUnique(CPPPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'include')])
-env.AppendUnique(LIBPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'lib', target_arch)])
+if target_os not in ['windows']:
+       env.AppendUnique(CPPPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'include')])
+       env.AppendUnique(LIBPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'lib', target_arch)])
 
 # Check whether a library exists, if not, notify user to install it or try to
 # download the source code and build it
diff --git a/build_common/msys_nt/SConscript b/build_common/msys_nt/SConscript
new file mode 100644 (file)
index 0000000..140f54b
--- /dev/null
@@ -0,0 +1,33 @@
+##
+# This script sets compiler flags for 
+# MinGW in the MSYS environment.
+##
+Import('env')
+
+# Set common flags
+# Overwrite suffixes and prefixes
+if env['TARGET_OS'] == 'msys_nt':
+       env['SHLIBPREFIX'] = 'lib'
+
+env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+
+target_arch = env.get('TARGET_ARCH')
+
+if env['CC'] == 'gcc':
+       if env.get('RELEASE'):
+               env.AppendUnique(CCFLAGS = ['-Os'])
+               env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+       else:
+               env.AppendUnique(CCFLAGS = ['-g'])
+       env.AppendUnique(CFLAGS = ['-std=c99'])
+       env.AppendUnique(CXXFLAGS = ['-std=c++11'])
+       env.AppendUnique(CCFLAGS = ['-Wall', '-Wextra', '-Wa,-mbig-obj'])
+       env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '_GNU_SOURCE', '__msys_nt__', '_WIN32_WINNT=0x0600'])
+       
+       # Set arch flags
+       if target_arch in ['x86']:
+               env.AppendUnique(CCFLAGS = ['-m32'])
+               env.AppendUnique(LINKFLAGS = ['-m32'])
+       elif target_arch in ['x86_64']:
+               env.AppendUnique(CCFLAGS = ['-m64'])
+               env.AppendUnique(LINKFLAGS = ['-m64'])
index 0df17e4..514b54c 100644 (file)
@@ -307,48 +307,55 @@ def generate( env ) :
     # read tools for Windows system
     if env["PLATFORM"] <> "darwin" and "win" in env["PLATFORM"] :
 
-        if env.WhereIs("7z") :
+        if env.WhereIs('7z', env.get('PATH')):
             toolset["EXTRACTOR"]["TARGZ"]["RUN"]           = "7z"
             toolset["EXTRACTOR"]["TARGZ"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
             toolset["EXTRACTOR"]["TARGZ"]["LISTFLAGS"]     = "x"
             toolset["EXTRACTOR"]["TARGZ"]["LISTSUFFIX"]    = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} l -sii -ttar -y -so"
             toolset["EXTRACTOR"]["TARGZ"]["EXTRACTFLAGS"]  = "x"
-            toolset["EXTRACTOR"]["TARGZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -oc:${UNPACK['EXTRACTDIR']}"
+            toolset["EXTRACTOR"]["TARGZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -o${UNPACK['EXTRACTDIR']}"
 
             toolset["EXTRACTOR"]["TARBZ"]["RUN"]           = "7z"
             toolset["EXTRACTOR"]["TARBZ"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
             toolset["EXTRACTOR"]["TARBZ"]["LISTFLAGS"]     = "x"
             toolset["EXTRACTOR"]["TARBZ"]["LISTSUFFIX"]    = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} l -sii -ttar -y -so"
             toolset["EXTRACTOR"]["TARBZ"]["EXTRACTFLAGS"]  = "x"
-            toolset["EXTRACTOR"]["TARBZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -oc:${UNPACK['EXTRACTDIR']}"
+            toolset["EXTRACTOR"]["TARBZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -o${UNPACK['EXTRACTDIR']}"
 
             toolset["EXTRACTOR"]["BZIP"]["RUN"]            = "7z"
             toolset["EXTRACTOR"]["BZIP"]["LISTEXTRACTOR"]  = __fileextractor_win_7zip
             toolset["EXTRACTOR"]["BZIP"]["LISTFLAGS"]      = "l"
             toolset["EXTRACTOR"]["BZIP"]["LISTSUFFIX"]     = "-y -so"
             toolset["EXTRACTOR"]["BZIP"]["EXTRACTFLAGS"]   = "x"
-            toolset["EXTRACTOR"]["BZIP"]["EXTRACTSUFFIX"]  = "-y -oc:${UNPACK['EXTRACTDIR']}"
+            toolset["EXTRACTOR"]["BZIP"]["EXTRACTSUFFIX"]  = "-y -o${UNPACK['EXTRACTDIR']}"
 
             toolset["EXTRACTOR"]["GZIP"]["RUN"]            = "7z"
             toolset["EXTRACTOR"]["GZIP"]["LISTEXTRACTOR"]  = __fileextractor_win_7zip
             toolset["EXTRACTOR"]["GZIP"]["LISTFLAGS"]      = "l"
             toolset["EXTRACTOR"]["GZIP"]["LISTSUFFIX"]     = "-y -so"
             toolset["EXTRACTOR"]["GZIP"]["EXTRACTFLAGS"]   = "x"
-            toolset["EXTRACTOR"]["GZIP"]["EXTRACTSUFFIX"]  = "-y -oc:${UNPACK['EXTRACTDIR']}"
+            toolset["EXTRACTOR"]["GZIP"]["EXTRACTSUFFIX"]  = "-y -o${UNPACK['EXTRACTDIR']}"
 
             toolset["EXTRACTOR"]["ZIP"]["RUN"]             = "7z"
             toolset["EXTRACTOR"]["ZIP"]["LISTEXTRACTOR"]   = __fileextractor_win_7zip
             toolset["EXTRACTOR"]["ZIP"]["LISTFLAGS"]       = "l"
             toolset["EXTRACTOR"]["ZIP"]["LISTSUFFIX"]      = "-y -so"
             toolset["EXTRACTOR"]["ZIP"]["EXTRACTFLAGS"]    = "x"
-            toolset["EXTRACTOR"]["ZIP"]["EXTRACTSUFFIX"]   = "-y -oc:${UNPACK['EXTRACTDIR']}"
+            toolset["EXTRACTOR"]["ZIP"]["EXTRACTSUFFIX"]   = "-y -o${UNPACK['EXTRACTDIR']}"
 
             toolset["EXTRACTOR"]["TAR"]["RUN"]             = "7z"
             toolset["EXTRACTOR"]["TAR"]["LISTEXTRACTOR"]   = __fileextractor_win_7zip
             toolset["EXTRACTOR"]["TAR"]["LISTFLAGS"]       = "l"
             toolset["EXTRACTOR"]["TAR"]["LISTSUFFIX"]      = "-y -ttar -so"
             toolset["EXTRACTOR"]["TAR"]["EXTRACTFLAGS"]    = "x"
-            toolset["EXTRACTOR"]["TAR"]["EXTRACTSUFFIX"]   = "-y -ttar -oc:${UNPACK['EXTRACTDIR']}"
+            toolset["EXTRACTOR"]["TAR"]["EXTRACTSUFFIX"]   = "-y -ttar -o${UNPACK['EXTRACTDIR']}"
+        else:
+            print '''*********************** Error ************************
+*                                                    *
+* Please make sure that 7-zip is in your System PATH *
+*                                                    *
+******************************************************
+'''
 
         # here can add some other Windows tools, that can handle the archive files
         # but I don't know which ones can handle all file types
@@ -356,7 +363,7 @@ def generate( env ) :
 
 
     # read the tools on *nix systems and sets the default parameters
-    elif env["PLATFORM"] in ["darwin", "linux", "posix"] :
+    elif env["PLATFORM"] in ["darwin", "linux", "posix", "msys"] :
 
         if env.WhereIs("unzip") :
             toolset["EXTRACTOR"]["ZIP"]["RUN"]             = "unzip"
index 4c35d35..39e7fd2 100644 (file)
@@ -2,16 +2,44 @@
 # This script includes windows specific config (MSVS/MSVC)
 ##
 Import('env')
+import os.path
 
 # Set common flags
-env.AppendUnique(CXXFLAGS=['/wd4244', '/wd4267','/wd4345', '/wd4355', '/wd4800', '/wd4996'])
-env.AppendUnique(CCFLAGS=['/EHsc'])
+if env['CC'] == 'cl':
+
+    # TODO: re-enable warnings, especially: 4244, 4267, 4365
+    env.AppendUnique(CXXFLAGS=[
+        '/wd4244',   # C4244 conversion from one type to another type results in a possible loss of data.
+        '/wd4267',   # C4267 conversion from size_t to a smaller type.
+        '/wd4355',   # C4355 'this' used in base member initializer list.
+        '/wd4800',   # C4800 forcing value to bool 'true' or 'false'.
+        '/wd4996',   # C4996 deprecated declaration.
+        '/wd4820',   # C4820 added padding to the end of a struct.
+        '/wd4514',   # C4514 unreferenced inline function has been removed
+        '/wd4365',   # C4365 signed/unsigned mismatch
+        '/wd4503'])  # C4503 decorated name length exceeded, name was truncated
+
+    env.AppendUnique(CCFLAGS=['/EHsc'])
+
+    vs_version = env['MSVC_VERSION']
+
+    # Enable special exports for unit test purposes
+    if env.get('TEST') == '1':
+        env.AppendUnique(CPPDEFINES = ['ENABLE_TEST_EXPORTS'])
+    # 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'])
+    env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+    env.AppendUnique(PATH = os.environ['PATH'])
+
+elif env['CC'] == 'gcc':
+    print "\nError: gcc not supported on Windows.  Use Visual Studio!\n"
+    Exit(1);
 
-# Set release/debug flags
-if env.get('RELEASE'):
-       env.AppendUnique(CCFLAGS = ['/MD', '/O2', '/GF'])
-       env.AppendUnique(CPPDEFINES = ['NDEBUG'])
-else:
-       env.AppendUnique(CCFLAGS = ['/MDd', '/Od', '/ZI', '/GZ', '/Gm'])
-       env.AppendUnique(CPPDEFINES = ['_DEBUG'])
-       env.AppendUnique(LINKFLAGS = ['/debug'])
index e8ed300..f9f3c85 100644 (file)
@@ -40,7 +40,7 @@ examples_env.AppendUnique(CPPPATH = [
                ])
 
 target_os = env.get('TARGET_OS')
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
        examples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
 
        # Note: 'pthread' is in libc for android. On other platform, if use
index 472ce12..684370b 100644 (file)
@@ -88,8 +88,9 @@ protected:
     WrapRequest *m_typeRequest;
 };
 
-struct WrapRequest
+class WrapRequest
 {
+public:
     WrapRequest(WrapResource *wres, RequestType type, token_t token);
 
     friend class WrapResource;
index c9fa5cf..76fb4ec 100644 (file)
@@ -8,24 +8,72 @@ modules = ['thread','program_options', 'system', 'date_time']
 
 target_os = env.get('TARGET_OS')
 target_arch = env.get('TARGET_ARCH')
+src_dir = env.get('SRC_DIR')
+
+boost_version   = '1.60.0'
+
+# TODO: Remove coupling between build scripts and 1_58_0 version for Android
+if target_os in ['android']:
+    boost_version   = '1.58.0'
+
+boost_base_name  = 'boost_'+string.replace(boost_version,'.','_')
+boost_arch_name  = boost_base_name+'.zip'
+boost_b2_name    = boost_base_name+os.sep+'b2'
+boost_url       = 'http://downloads.sourceforge.net/project/boost/boost/'+boost_version+'/'+boost_arch_name+'?r=&ts=1421801329&use_mirror=iweb'
+
+boost_dir = os.path.join(src_dir,'extlibs','boost','boost')
+boost_bootstrap = os.path.join(boost_dir,'bootstrap.bat')
 
 if 'linux' == target_os :
     # Check for Boost libraries in /usr/boost
     print 'TODO: Perform platform check for linux'
     raise SCons.Errors.EnvironmentError('Unsupported platform')
 
-if 'android' == target_os :
+elif target_os in ['windows']:
+    boost_zip_file   = os.path.join(src_dir,'extlibs','boost',boost_arch_name)
+
+    if not os.path.exists(boost_bootstrap):
+
+        # Download if necessary
+        if os.path.exists(boost_zip_file):
+            boost_zip = boost_zip_file
+        else:
+            print '*** Downloading Boost zip file (> 100MB). Please wait... ***'
+            boost_zip = env.Download(boost_zip_file, boost_url)
+
+        # Unzip boost
+        print '*** Unpacking boost %s zip file ... ***' % boost_version
+        env.UnpackAll(boost_dir, boost_zip)
+
+        # Rename from boost_1_60_0 -> boost
+        os.rename(boost_base_name, 'boost')
+
+    # Sanity check, in case the above method didn't work
+    if not os.path.exists(boost_bootstrap):
+        print '''
+*********************************** Error: ****************************************
+* Please download boost from the following website:
+*
+*   ''' + boost_url + '''
+*
+* and extract the contents directly into
+*
+*    ''' + boost_dir + '''
+*
+* such that this build system can find:
+*
+* ''' + boost_bootstrap + '''
+*
+***********************************************************************************
+'''
+        Exit(1)
+
+elif target_os in ['android']:
     env.Tool('URLDownload',    toolpath=['../../tools/scons'])
     env.Tool('UnpackAll',      toolpath=['../../tools/scons'])
     env.Tool('BoostBootstrap', toolpath=['../../tools/scons'])
     env.Tool('BoostBuild',     toolpath=['../../tools/scons'])
 
-    boost_version   = '1.58.0'
-    boost_base_name  = 'boost_'+string.replace(boost_version,'.','_')
-    boost_arch_name  = boost_base_name+'.zip'
-    boost_b2_name    = boost_base_name+os.sep+'b2'
-    boost_url       = 'http://downloads.sourceforge.net/project/boost/boost/'+boost_version+'/'+boost_arch_name+'?r=&ts=1421801329&use_mirror=iweb'
-
     host_os = sys.platform
 
     if host_os == 'linux2' :
index 867b7c3..eef7b8b 100644 (file)
@@ -39,6 +39,8 @@ extern "C"
        
 #define cJSON_IsReference 256
 
+#include <platform_features.h>
+
 /* The cJSON structure: */
 typedef struct cJSON {
        struct cJSON *next,*prev;       /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
@@ -59,71 +61,71 @@ typedef struct cJSON_Hooks {
 } cJSON_Hooks;
 
 /* Supply malloc, realloc and free functions to cJSON */
-extern void cJSON_InitHooks(cJSON_Hooks* hooks);
+OC_EXPORT extern void cJSON_InitHooks(cJSON_Hooks* hooks);
 
 
 /* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
-extern cJSON *cJSON_Parse(const char *value);
+OC_EXPORT extern cJSON *cJSON_Parse(const char *value);
 /* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
-extern char  *cJSON_Print(cJSON *item);
+OC_EXPORT extern char  *cJSON_Print(cJSON *item);
 /* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
-extern char  *cJSON_PrintUnformatted(cJSON *item);
+OC_EXPORT extern char  *cJSON_PrintUnformatted(cJSON *item);
 /* Delete a cJSON entity and all subentities. */
-extern void   cJSON_Delete(cJSON *c);
+OC_EXPORT extern void   cJSON_Delete(cJSON *c);
 
 /* Returns the number of items in an array (or object). */
-extern int       cJSON_GetArraySize(cJSON *array);
+OC_EXPORT extern int     cJSON_GetArraySize(cJSON *array);
 /* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
-extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
+OC_EXPORT extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
 /* Get item "string" from object. Case insensitive. */
-extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
+OC_EXPORT extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
 
 /* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
-extern const char *cJSON_GetErrorPtr(void);
-       
+OC_EXPORT extern const char *cJSON_GetErrorPtr(void);
+
 /* These calls create a cJSON item of the appropriate type. */
-extern cJSON *cJSON_CreateNull(void);
-extern cJSON *cJSON_CreateTrue(void);
-extern cJSON *cJSON_CreateFalse(void);
-extern cJSON *cJSON_CreateBool(int b);
-extern cJSON *cJSON_CreateNumber(double num);
-extern cJSON *cJSON_CreateString(const char *string);
-extern cJSON *cJSON_CreateArray(void);
-extern cJSON *cJSON_CreateObject(void);
+OC_EXPORT extern cJSON *cJSON_CreateNull(void);
+OC_EXPORT extern cJSON *cJSON_CreateTrue(void);
+OC_EXPORT extern cJSON *cJSON_CreateFalse(void);
+OC_EXPORT extern cJSON *cJSON_CreateBool(int b);
+OC_EXPORT extern cJSON *cJSON_CreateNumber(double num);
+OC_EXPORT extern cJSON *cJSON_CreateString(const char *string);
+OC_EXPORT extern cJSON *cJSON_CreateArray(void);
+OC_EXPORT extern cJSON *cJSON_CreateObject(void);
 
 /* These utilities create an Array of count items. */
-extern cJSON *cJSON_CreateIntArray(const int *numbers,int count);
-extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count);
-extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count);
-extern cJSON *cJSON_CreateStringArray(const char **strings,int count);
+OC_EXPORT extern cJSON *cJSON_CreateIntArray(const int *numbers,int count);
+OC_EXPORT extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count);
+OC_EXPORT extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count);
+OC_EXPORT extern cJSON *cJSON_CreateStringArray(const char **strings,int count);
 
 /* Append item to the specified array/object. */
-extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
-extern void    cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
+OC_EXPORT extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
+OC_EXPORT extern void  cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
 /* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
-extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
-extern void    cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item);
+OC_EXPORT extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
+OC_EXPORT extern void  cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item);
 
 /* Remove/Detatch items from Arrays/Objects. */
-extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which);
-extern void   cJSON_DeleteItemFromArray(cJSON *array,int which);
-extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string);
-extern void   cJSON_DeleteItemFromObject(cJSON *object,const char *string);
-       
+OC_EXPORT extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which);
+OC_EXPORT extern void   cJSON_DeleteItemFromArray(cJSON *array,int which);
+OC_EXPORT extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string);
+OC_EXPORT extern void   cJSON_DeleteItemFromObject(cJSON *object,const char *string);
+
 /* Update array items. */
-extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem);
-extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
+OC_EXPORT extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem);
+OC_EXPORT extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
 
 /* Duplicate a cJSON item */
-extern cJSON *cJSON_Duplicate(cJSON *item,int recurse);
+OC_EXPORT extern cJSON *cJSON_Duplicate(cJSON *item,int recurse);
 /* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
 need to be released. With recurse!=0, it will duplicate any children connected to the item.
 The item->next and ->prev pointers are always zero on return from Duplicate. */
 
 /* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
-extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated);
+OC_EXPORT extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated);
 
-extern void cJSON_Minify(char *json);
+OC_EXPORT extern void cJSON_Minify(char *json);
 
 /* Macros for creating things quickly. */
 #define cJSON_AddNullToObject(object,name)             cJSON_AddItemToObject(object, name, cJSON_CreateNull())
index 6ecdcd1..a751ca3 100644 (file)
@@ -11,14 +11,13 @@ Import('env')
 target_os = env.get('TARGET_OS')
 src_dir = env.get('SRC_DIR')
 
-targets_need_gtest = ['darwin','linux']
-gtest_dir      = src_dir + '/extlibs/gtest/gtest-1.7.0'
-gtest_zip_file = src_dir + '/extlibs/gtest/gtest-1.7.0.zip'
+targets_need_gtest = ['darwin','linux', 'msys_nt', 'windows']
+gtest_dir      = os.path.join(src_dir, 'extlibs', 'gtest', 'gtest-1.7.0')
+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'
 
 if target_os in targets_need_gtest:
        print '*** Checking for installation of google unit test 1.7.0 ***'
-
        if not os.path.exists(gtest_dir):
                # If the gtest zip file is not already present, download it
                if not os.path.exists(gtest_zip_file):
@@ -27,8 +26,9 @@ if target_os in targets_need_gtest:
                        gtest_zip = gtest_zip_file
 
                # Unzip gtest
-               print 'Unzipping google unit test'
-               env.UnpackAll(gtest_dir, gtest_zip)
+               if not os.path.exists(os.path.join(gtest_dir, 'configure')):
+                       print 'Unzipping google unit test'
+                       env.UnpackAll(gtest_dir, gtest_zip)
 
 
 if target_os == 'darwin':
@@ -70,12 +70,103 @@ elif target_os == 'linux':
                        # Run configure on gtest
                        print 'Configuring google unit test'
                        if env.get('CROSS_COMPILE'):
-                               env.Configure(gtest_dir, './configure --host=' + env['CROSS_COMPILE'])
+                               env.Configure(gtest_dir, './configure --disable-shared --host=' + env['CROSS_COMPILE'])
                        else:
-                               env.Configure(gtest_dir, './configure')
+                               env.Configure(gtest_dir, './configure --disable-shared')
+                       # Run make on gtest
+                       print 'Making google unit test'
+                       env.Configure(gtest_dir, 'make')
+
+
+elif target_os == 'msys_nt':
+       if os.path.exists(gtest_dir):
+               gtest_lib_dir = gtest_dir + '/lib'
+               gtest_dotlib_dir = gtest_lib_dir + '/.libs'
+               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'
+                       env.Configure(gtest_dir, 'cmake -G "Unix Makefiles" .')
 
                        # Run make on gtest
                        print 'Making google unit test'
                        env.Configure(gtest_dir, 'make')
 
+                       print 'Moving libraries to lib folder'
+                       env.Configure(gtest_dir, 'cp libgtest.a lib')
+                       env.Configure(gtest_dir, 'mv libgtest.a lib/.libs')
+                       env.Configure(gtest_dir, 'cp libgtest_main.a lib')
+                       env.Configure(gtest_dir, 'mv libgtest_main.a lib/.libs')
+
+elif target_os == 'windows':
+       if os.path.exists(gtest_dir):
+               gtest_lib_dir = os.path.join(gtest_dir, 'lib')
+               gtest_dotlib_dir = os.path.join(gtest_lib_dir, '.libs')
+               if 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 env.WhereIs('cmake', 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'
+                       env.Configure(gtest_dir, 'cmake . -G"'+vs_target_string+'" -Dgtest_force_shared_crt=ON')
+
+                       # Run make on gtest
+                       print 'Making google unit test'
+                       env.Configure(gtest_dir, 'msbuild gtest.vcxproj')
+                       env.Configure(gtest_dir, 'msbuild gtest_main.vcxproj')
+
+                       print 'Moving libraries to lib folder'
+                       env.Configure(gtest_dir, 'copy '+output_dir+'gtest.lib %s' % gtest_lib_dir)
+                       env.Configure(gtest_dir, 'move '+output_dir+'gtest.lib %s' % gtest_dotlib_dir )
+                       env.Configure(gtest_dir, 'copy '+output_dir+'gtest_main.lib %s' % gtest_lib_dir)
+                       env.Configure(gtest_dir, 'move '+output_dir+'gtest_main.lib %s' % gtest_dotlib_dir)
 
index 6d5b5a4..f756abf 100644 (file)
@@ -35,7 +35,7 @@ src_dir = env.get('SRC_DIR')
 if target_os == 'linux':
        print '*** Checking for installation of hippomocks ***'
 
-       hippomocks_sha      = '2f40aa11e31499432283b67f9d3449a3cd7b9c4d'
+       hippomocks_sha      = '8e210c5808d490b26fff69151c801fa28d291fcb'
        hippomocks_dir_src  = src_dir + '/extlibs/hippomocks-' + hippomocks_sha
        hippomocks_dir_dest = src_dir + '/extlibs/hippomocks-master'
        hippomocks_zip_file = src_dir + '/extlibs/hippomocks-' + hippomocks_sha + '.zip'
index 41c65df..a7e033b 100755 (executable)
@@ -11,11 +11,11 @@ sqlite_env = env.Clone()
 target_os = sqlite_env.get('TARGET_OS')
 src_dir = sqlite_env.get('SRC_DIR')
 
-targets_need_sqlite = ['linux', 'android', 'tizen']
+targets_need_sqlite = ['linux', 'android', 'tizen', 'msys_nt', 'windows']
 sqlite_dir      = src_dir + '/extlibs/sqlite3/'
 sqlite_build_dir      = src_dir + '/extlibs/sqlite3/sqlite-amalgamation-3081101/'
 sqlite_zip_file = src_dir + '/extlibs/sqlite3/sqlite-amalgamation-3081101.zip'
-sqlite_url      = 'http://www.sqlite.org/2015/sqlite-amalgamation-3081101.zip'
+sqlite_url      = 'https://www.sqlite.org/2015/sqlite-amalgamation-3081101.zip'
 
 # Download
 if target_os in targets_need_sqlite:
@@ -39,4 +39,4 @@ if target_os in targets_need_sqlite:
                os.remove(sqlite_zip_file)
                shutil.rmtree(sqlite_build_dir)
 
-# Build will be done with provisioning manager module.
\ No newline at end of file
+# Build will be done with provisioning manager module.
index edcc7ef..33d134a 100644 (file)
 # *****************************************************************/
 
 Import('env')
-env.AppendUnique(TIMER_SRC = 'timer.c')
-
-libtimer = env.StaticLibrary('libtimer', env.get('TIMER_SRC'), OBJPREFIX='libtimer_')
-env.InstallTarget(libtimer, 'libtimer');
 
+timer_src = [ 'timer.c' ]
 
+libtimer = env.StaticLibrary('timer', timer_src, OBJPREFIX='libtimer_')
+env.InstallTarget(libtimer, 'timer');
 
index 43043a6..3dda84b 100755 (executable)
 
 #define _BSD_SOURCE
 
-#ifndef WITH_ARDUINO
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
+#endif
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_MEMORY_H
 #include <memory.h>
+#endif
+#ifdef HAVE_STDLIB_H
 #include <stdlib.h>
 #endif
-
+#ifdef HAVE_STRING_H
 #include <string.h>
+#endif
+#include "platform_features.h"
+
 #include <stdio.h>
 
 #include "timer.h"
@@ -254,10 +266,7 @@ void *loop(void *threadid)
 
 int initThread()
 {
-    int res;
-    long t = 0;
-
-    res = pthread_create(&thread_id, NULL, loop, (void *) t);
+    int res = pthread_create(&thread_id, NULL, loop, NULL);
 
     if (res)
     {
index 3ecff36..3ad432a 100644 (file)
 #ifndef TIMER_H_
 #define TIMER_H_
 
-#ifndef WITH_ARDUINO
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
-#else
+#endif
+#ifdef HAVE_ARDUINO_TIME_H
 #include <Time.h>
 #endif
 
index 5d186a2..0d1bf93 100644 (file)
@@ -40,9 +40,6 @@ dtls_env.AppendUnique(CPPPATH = [root_dir+'aes/'])
 dtls_env.AppendUnique(CPPPATH = [root_dir+'ecc/'])
 dtls_env.AppendUnique(CPPPATH = [root_dir+'sha2/'])
 
-if target_os not in ['arduino', 'windows', 'winrt']:
-       dtls_env.AppendUnique(CPPDEFINES = ['HAVE_SYS_TIME_H'])
-
 ######################################################################
 # Source files and Target(s)
 ######################################################################
@@ -84,7 +81,7 @@ libtinydtls = dtls_env.StaticLibrary('tinydtls', tinydtls_src, OBJPREFIX='libtin
 if not env.get('RELEASE'):
        samples_env = dtls_env.Clone()
 
-       if target_os not in ['arduino', 'windows', 'winrt']:
+       if target_os not in ['arduino', 'windows']:
                samples_env.AppendUnique(CPPDEFINES = ['_GNU_SOURCE'])
 
        dtlsserver = samples_env.Program('dtls-server', ['tests/dtls-server.c'])
@@ -93,6 +90,9 @@ if not env.get('RELEASE'):
        samples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
        samples_env.PrependUnique(LIBS = ['tinydtls'])
 
+       if target_os in ['windows', 'msys_nt']:
+               samples_env.AppendUnique(LIBS = ['ws2_32', 'iphlpapi', 'advapi32'])
+
        Alias("samples", [dtlsserver, dtlsclient])
 
        samples_env.AppendTarget('samples')
index 5a27faa..a589dd7 100644 (file)
@@ -66,13 +66,13 @@ typedef enum {
                                          * has finished */
 #define DTLS_EVENT_RENEGOTIATE    0x01DF /**< re-negotiation has started */
 
-static inline int
+INLINE_API int
 dtls_alert_create(dtls_alert_level_t level, dtls_alert_t desc)
 {
   return -((level << 8) | desc);
 }
 
-static inline int
+INLINE_API int
 dtls_alert_fatal_create(dtls_alert_t desc)
 {
   return dtls_alert_create(DTLS_ALERT_LEVEL_FATAL, desc);
index 7563db8..1366145 100644 (file)
@@ -46,7 +46,7 @@
       (A)[i] |= (C) & 0xFF;                                            \
   }
 
-static inline void 
+INLINE_API void 
 block0(size_t M,       /* number of auth bytes */
        size_t L,       /* number of bytes to encode message length */
        size_t la,      /* l(a) octets additional authenticated data */
@@ -145,7 +145,7 @@ add_auth_data(rijndael_ctx *ctx, const unsigned char *msg, size_t la,
   } 
 }
 
-static inline void
+INLINE_API void
 encrypt(rijndael_ctx *ctx, size_t L, unsigned long counter,
        unsigned char *msg, size_t len,
        unsigned char A[DTLS_CCM_BLOCKSIZE],
@@ -158,7 +158,7 @@ encrypt(rijndael_ctx *ctx, size_t L, unsigned long counter,
   memxor(msg, S, len);
 }
 
-static inline void
+INLINE_API void
 mac(rijndael_ctx *ctx, 
     unsigned char *msg, size_t len,
     unsigned char B[DTLS_CCM_BLOCKSIZE],
index de07f49..d9ec048 100644 (file)
@@ -60,7 +60,7 @@
 #include "netq.h"
 #include "hmac.h"
 
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
 #include <pthread.h>
 #endif
 
   if (Seed) dtls_hmac_update(Context, (Seed), (Length))
 
 static struct dtls_cipher_context_t cipher_context;
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
 static pthread_mutex_t cipher_context_mutex = PTHREAD_MUTEX_INITIALIZER;
 #endif
 
 static struct dtls_cipher_context_t *dtls_cipher_context_get(void)
 {
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
   pthread_mutex_lock(&cipher_context_mutex);
 #endif
   return &cipher_context;
@@ -82,7 +82,7 @@ static struct dtls_cipher_context_t *dtls_cipher_context_get(void)
 
 static void dtls_cipher_context_release(void)
 {
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
   pthread_mutex_unlock(&cipher_context_mutex);
 #endif
 }
index 8ea83f2..8acf787 100644 (file)
@@ -158,7 +158,7 @@ typedef struct {
 /* The following macros provide access to the components of the
  * key_block in the security parameters. */
 
-static inline int dtls_kb_mac_secret_size(dtls_cipher_t cipher)
+INLINE_API int dtls_kb_mac_secret_size(dtls_cipher_t cipher)
 {
     switch(cipher)
     {
@@ -184,7 +184,7 @@ static inline int dtls_kb_mac_secret_size(dtls_cipher_t cipher)
 }
 
 
-static inline int dtls_kb_iv_size(dtls_cipher_t cipher)
+INLINE_API int dtls_kb_iv_size(dtls_cipher_t cipher)
 {
     switch(cipher)
     {
index 589c091..5b458bc 100644 (file)
@@ -87,7 +87,7 @@ static char *loglevels[] = {
 
 #ifdef HAVE_TIME_H
 
-static inline size_t
+INLINE_API size_t
 print_timestamp(char *s, size_t len, time_t t) {
   struct tm *tmp;
   tmp = localtime(&t);
@@ -96,7 +96,7 @@ print_timestamp(char *s, size_t len, time_t t) {
 
 #else /* alternative implementation: just print the timestamp */
 
-static inline size_t
+INLINE_API size_t
 print_timestamp(char *s, size_t len, clock_time_t t) {
 #ifdef HAVE_SNPRINTF
   return snprintf(s, len, "%u.%03u", 
@@ -118,7 +118,7 @@ print_timestamp(char *s, size_t len, clock_time_t t) {
  * 
  * @return The length of @p s.
  */
-static inline size_t
+INLINE_API size_t
 dtls_strnlen(const char *s, size_t maxlen) {
   size_t n = 0;
   while(*s++ && n < maxlen)
@@ -132,9 +132,9 @@ dtls_strnlen(const char *s, size_t maxlen) {
 
 static size_t
 dsrv_print_addr(const session_t *addr, char *buf, size_t len) {
-#ifdef HAVE_ARPA_INET_H
+#if defined(HAVE_ARPA_INET_H) || defined(_WIN32)
   const void *addrptr = NULL;
-#ifdef __ANDROID__
+#if defined(__ANDROID__) || defined(_WIN32)
   unsigned short int port;
 #else
   in_port_t port;
index 95286f8..89af876 100644 (file)
@@ -41,7 +41,7 @@
 #ifdef CONTIKI_TARGET_MBXXX
 extern char __Stack_Init, _estack;
 
-static inline void check_stack() {
+INLINE_API void check_stack() {
   const char *p = &__Stack_Init;
   while (p < &_estack && *p == 0x38) {
     p++;
@@ -50,13 +50,13 @@ static inline void check_stack() {
   PRINTF("Stack: %d bytes used (%d free)\n", &_estack - p, p - &__Stack_Init);
 }
 #else /* CONTIKI_TARGET_MBXXX */
-static inline void check_stack() {
+INLINE_API void check_stack() {
 }
 #endif /* CONTIKI_TARGET_MBXXX */
 #else /* WITH_CONTKI */
 #define PRINTF(...)
 
-static inline void check_stack() {
+INLINE_API void check_stack() {
 }
 #endif
 
@@ -102,28 +102,28 @@ void dtls_dsrv_log_addr(log_t level, const char *name, const session_t *addr);
 
 #else /* NDEBUG */
 
-static inline log_t dtls_get_log_level()
+INLINE_API log_t dtls_get_log_level()
 {
   return DTLS_LOG_EMERG;
 }
 
-static inline void dtls_set_log_level(log_t level)
+INLINE_API void dtls_set_log_level(log_t level)
 {}
 
-static inline void dsrv_log(log_t level, char *format, ...)
+INLINE_API void dsrv_log(log_t level, char *format, ...)
 {}
 
-static inline void hexdump(const unsigned char *packet, int length)
+INLINE_API void hexdump(const unsigned char *packet, int length)
 {}
 
-static inline void dump(unsigned char *buf, size_t len)
+INLINE_API void dump(unsigned char *buf, size_t len)
 {}
 
-static inline void
+INLINE_API void
 dtls_dsrv_hexdump_log(log_t level, const char *name, const unsigned char *buf, size_t length, int extend)
 {}
 
-static inline void
+INLINE_API void
 dtls_dsrv_log_addr(log_t level, const char *name, const struct __session_t *addr)
 {}
 
index 6cf26b4..1017346 100644 (file)
@@ -138,23 +138,23 @@ PROCESS(dtls_retransmit_process, "DTLS retransmit process");
 
 static dtls_context_t the_dtls_context;
 
-static inline dtls_context_t *
+INLINE_API dtls_context_t *
 malloc_context() {
   return &the_dtls_context;
 }
 
-static inline void
+INLINE_API void
 free_context(dtls_context_t *context) {
 }
 
 #else /* WITH_CONTIKI */
 
-static inline dtls_context_t *
+INLINE_API dtls_context_t *
 malloc_context() {
   return (dtls_context_t *)malloc(sizeof(dtls_context_t));
 }
 
-static inline void
+INLINE_API void
 free_context(dtls_context_t *context) {
   free(context);
 }
@@ -227,6 +227,16 @@ dtls_send(dtls_context_t *ctx, dtls_peer_t *peer, unsigned char type,
  */
 static void dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer);
 
+/**
+ * Starts retransmissions of handshake messages for @p peer.
+ */
+static void dtls_start_retransmission(dtls_context_t *context, dtls_peer_t *peer);
+
+/**
+ * Clears retransmissions of handshake messages for @p peer.
+ */
+static void dtls_clear_retransmission(dtls_context_t *context, dtls_peer_t *peer);
+
 dtls_peer_t *
 dtls_get_peer(const dtls_context_t *ctx, const session_t *session) {
   dtls_peer_t *p = NULL;
@@ -405,7 +415,7 @@ is_record(uint8 *msg, size_t msglen) {
  * \return pointer to the next byte after the written header.
  * The length will be set to 0 and has to be changed before sending.
  */ 
-static inline uint8 *
+INLINE_API uint8 *
 dtls_set_record_header(uint8 type, dtls_security_parameters_t *security,
                       uint8 *buf) {
   
@@ -439,7 +449,7 @@ dtls_set_record_header(uint8 type, dtls_security_parameters_t *security,
  * bytes. Increments message sequence number counter of \p peer.
  * \return pointer to the next byte after \p buf
  */ 
-static inline uint8 *
+INLINE_API uint8 *
 dtls_set_handshake_header(uint8 type, dtls_peer_t *peer, 
                          int length, 
                          int frag_offset, int frag_length, 
@@ -477,7 +487,7 @@ static uint8 compression_methods[] = {
 };
 
 /** returns true if the cipher matches TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
-static inline int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
+INLINE_API int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
 {
 #if defined(DTLS_ECC) || defined(DTLS_X509)
   return cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
@@ -487,7 +497,7 @@ static inline int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
 }
 
 /** returns true if the cipher matches TLS_PSK_WITH_AES_128_CCM_8 */
-static inline int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
+INLINE_API int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
 {
 #ifdef DTLS_PSK
   return cipher == TLS_PSK_WITH_AES_128_CCM_8;
@@ -497,7 +507,7 @@ static inline int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
 }
 
 /** returns true if the cipher matches TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 */
-static inline int is_tls_ecdh_anon_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
+INLINE_API int is_tls_ecdh_anon_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
 {
 #ifdef DTLS_ECC
     return cipher == TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256;
@@ -507,7 +517,7 @@ static inline int is_tls_ecdh_anon_with_aes_128_cbc_sha_256(dtls_cipher_t cipher
 }
 
 /** returns true if the cipher matches TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 */
-static inline int is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
+INLINE_API int is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
 {
 #if defined(DTLS_ECC) && defined(DTLS_PSK)
   return cipher == TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256;
@@ -519,7 +529,7 @@ static inline int is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(dtls_cipher_t cipher
 
 
 /** returns true if the application is configured for psk */
-static inline int is_psk_supported(dtls_context_t *ctx)
+INLINE_API int is_psk_supported(dtls_context_t *ctx)
 {
 #ifdef DTLS_PSK
   return ctx && ctx->h && ctx->h->get_psk_info;
@@ -529,7 +539,7 @@ static inline int is_psk_supported(dtls_context_t *ctx)
 }
 
 /** returns true if the application is configured for ecdhe_ecdsa */
-static inline int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
+INLINE_API int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
 {
 #ifdef DTLS_ECC
   return ctx && ctx->h && ((!is_client && ctx->h->get_ecdsa_key) ||
@@ -540,7 +550,7 @@ static inline int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
 }
 
 /** returns true if the application is configured for x509 */
-static inline int is_x509_supported(dtls_context_t *ctx, int is_client)
+INLINE_API int is_x509_supported(dtls_context_t *ctx, int is_client)
 {
 #ifdef DTLS_X509
   return ctx && ctx->h && ((!is_client && ctx->h->get_x509_cert) ||
@@ -552,7 +562,7 @@ static inline int is_x509_supported(dtls_context_t *ctx, int is_client)
 
 /** Returns true if the application is configured for ecdhe_ecdsa with
   * client authentication */
-static inline int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
+INLINE_API int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
 {
 #ifdef DTLS_ECC
   return ctx && ctx->h && ctx->h->get_ecdsa_key && ctx->h->verify_ecdsa_key;
@@ -563,7 +573,7 @@ static inline int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
 
 /** Returns true if the application is configured for x509 with
   * client authentication */
-static inline int is_x509_client_auth_supported(dtls_context_t *ctx)
+INLINE_API int is_x509_client_auth_supported(dtls_context_t *ctx)
 {
 #ifdef DTLS_X509
   return ctx && ctx->h && ctx->h->get_x509_cert && ctx->h->verify_x509_cert;
@@ -573,7 +583,7 @@ static inline int is_x509_client_auth_supported(dtls_context_t *ctx)
 }
 
 /** returns true if ecdh_anon_with_aes_128_cbc_sha is supported */
-static inline int is_ecdh_anon_supported(dtls_context_t *ctx)
+INLINE_API int is_ecdh_anon_supported(dtls_context_t *ctx)
 {
 #ifdef DTLS_ECC
     return ctx &&  (ctx->is_anon_ecdh_eabled == DTLS_CIPHER_ENABLE);
@@ -583,7 +593,7 @@ static inline int is_ecdh_anon_supported(dtls_context_t *ctx)
 }
 
 /** returns true if ecdhe_psk_with_aes_128_cbc_sha_256 is supported */
-static inline int is_ecdhe_psk_supported(dtls_context_t *ctx)
+INLINE_API int is_ecdhe_psk_supported(dtls_context_t *ctx)
 {
 #if defined(DTLS_ECC) && defined(DTLS_PSK)
     return is_psk_supported(ctx);
@@ -1173,7 +1183,7 @@ error:
  * Parse the ClientKeyExchange and update the internal handshake state with
  * the new data.
  */
-static inline int
+INLINE_API int
 check_client_keyexchange(dtls_context_t *ctx, 
                         dtls_handshake_parameters_t *handshake,
                         uint8 *data, size_t length) {
@@ -1289,7 +1299,7 @@ check_client_keyexchange(dtls_context_t *ctx,
   return 0;
 }
 
-static inline void
+INLINE_API void
 update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length) {
   dtls_debug_dump("add MAC data", data, length);
   dtls_hash_update(&peer->handshake_params->hs_state.hs_hash, data, length);
@@ -1301,12 +1311,12 @@ copy_hs_hash(dtls_peer_t *peer, dtls_hash_ctx *hs_hash) {
         sizeof(peer->handshake_params->hs_state.hs_hash));
 }
 
-static inline size_t
+INLINE_API size_t
 finalize_hs_hash(dtls_peer_t *peer, uint8 *buf) {
   return dtls_hash_finalize(buf, &peer->handshake_params->hs_state.hs_hash);
 }
 
-static inline void
+INLINE_API void
 clear_hs_hash(dtls_peer_t *peer) {
   assert(peer);
   dtls_debug("clear MAC\n");
@@ -1755,7 +1765,7 @@ dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
   return res <= 0 ? res : overall_len - (len - res);
 }
 
-static inline int
+INLINE_API int
 dtls_send_alert(dtls_context_t *ctx, dtls_peer_t *peer, dtls_alert_level_t level,
                dtls_alert_t description) {
   uint8_t msg[] = { level, description };
@@ -2606,7 +2616,7 @@ dtls_send_server_hello_msgs(dtls_context_t *ctx, dtls_peer_t *peer)
   return 0;
 }
 
-static inline int 
+INLINE_API int 
 dtls_send_ccs(dtls_context_t *ctx, dtls_peer_t *peer) {
   uint8 buf[1] = {1};
 
@@ -3777,7 +3787,11 @@ handle_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
    * we do everything accordingly to the DTLS 1.2 standard this should
    * not be a problem. */
   if (peer) {
-    dtls_stop_retransmission(ctx, peer);
+    dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
+    if (state == DTLS_STATE_WAIT_CHANGECIPHERSPEC && hs_header->msg_type ==  DTLS_HT_FINISHED) {
+      return 0;
+    }
+    dtls_clear_retransmission(ctx, peer);
   }
 
   /* The following switch construct handles the given message with
@@ -4194,6 +4208,18 @@ handle_handshake(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
       return 0;
     }
   }
+  /* This is a ClientHello send when doing retransmission */
+  if (peer && hs_header->msg_type == DTLS_HT_CLIENT_HELLO &&
+              dtls_uint16_to_int(hs_header->message_seq) == 0) {
+     res = dtls_verify_peer(ctx, peer, session, state, data, data_length);
+     if (res < 0) {
+       dtls_warn("error in dtls_verify_peer err: %i\n", res);
+     }
+     if (res > 0) {
+       dtls_debug("server hello verify was sent\n");
+     }
+     return res;
+  }
 
   if (dtls_uint16_to_int(hs_header->message_seq) < peer->handshake_params->hs_state.mseq_r) {
     dtls_warn("The message sequence number is too small, expected %i, got: %i\n",
@@ -4366,7 +4392,7 @@ handle_alert(dtls_context_t *ctx, dtls_peer_t *peer,
   }
   
   if (free_peer) {
-    dtls_stop_retransmission(ctx, peer);
+    dtls_clear_retransmission(ctx, peer);
     dtls_destroy_peer(ctx, peer, 0);
   }
 
@@ -4439,23 +4465,28 @@ dtls_handle_message(dtls_context_t *ctx,
           state = DTLS_STATE_WAIT_CLIENTHELLO;
           role = DTLS_SERVER;
         } else {
-         int err =  dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
-          dtls_info("decrypt_verify() failed\n");
-         if (peer->state < DTLS_STATE_CONNECTED) {
-           dtls_alert_send_from_err(ctx, peer, &peer->session, err);
+         if (DTLS_CT_HANDSHAKE == msg[0] && DTLS_STATE_WAIT_FINISHED == peer->state) {
+           int err =  dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
+           dtls_info("decrypt_verify() failed\n");
 
-         (void)CALL(ctx, event, &peer->session,
-           DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
+           dtls_alert_send_from_err(ctx, peer, &peer->session, err);
 
+           (void)CALL(ctx, event, &peer->session,
+                   DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
            peer->state = DTLS_STATE_CLOSED;
-           /* dtls_stop_retransmission(ctx, peer); */
+                 /* dtls_clear_retransmission(ctx, peer); */
            dtls_destroy_peer(ctx, peer, 1);
+           return err;
+         } else {
+           data = msg + DTLS_RH_LENGTH;
+           data_length = rlen - DTLS_RH_LENGTH;
+           role = peer->role;
+           state = peer->state;
          }
-          return err;
-        }
+       }
       } else {
-        role = peer->role;
-        state = peer->state;
+       role = peer->role;
+       state = peer->state;
       }
     } else {
       /* is_record() ensures that msg contains at least a record header */
@@ -4476,9 +4507,6 @@ dtls_handle_message(dtls_context_t *ctx,
     switch (msg[0]) {
 
     case DTLS_CT_CHANGE_CIPHER_SPEC:
-      if (peer) {
-        dtls_stop_retransmission(ctx, peer);
-      }
       err = handle_ccs(ctx, peer, msg, data, data_length);
       if (err < 0) {
        dtls_warn("error while handling ChangeCipherSpec message\n");
@@ -4488,6 +4516,7 @@ dtls_handle_message(dtls_context_t *ctx,
                 DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
 
          /* invalidate peer */
+         dtls_clear_retransmission(ctx, peer);
          dtls_destroy_peer(ctx, peer, 1);
          peer = NULL;
         }
@@ -4497,7 +4526,7 @@ dtls_handle_message(dtls_context_t *ctx,
 
     case DTLS_CT_ALERT:
       if (peer) {
-        dtls_stop_retransmission(ctx, peer);
+        dtls_clear_retransmission(ctx, peer);
       }
       err = handle_alert(ctx, peer, msg, data, data_length);
       if (err < 0 || err == 1) {
@@ -4509,10 +4538,18 @@ dtls_handle_message(dtls_context_t *ctx,
       break;
 
     case DTLS_CT_HANDSHAKE:
+
       /* Handshake messages other than Finish must use the current
        * epoch, Finish has epoch + 1. */
 
       if (peer) {
+
+             /* Handle the client's last flight retransmission when the server's
+              * Finished message is lost. This avoids deadlock. */
+       if (DTLS_SERVER == role && DTLS_STATE_CONNECTED == state) {
+         dtls_start_retransmission(ctx, peer);
+         break;
+       }
        uint16_t expected_epoch = dtls_security_params(peer)->epoch;
        uint16_t msg_epoch = 
          dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
@@ -4565,7 +4602,7 @@ dtls_handle_message(dtls_context_t *ctx,
         // TODO: should we send a alert here?
         return -1;
       }
-      dtls_stop_retransmission(ctx, peer);
+      dtls_clear_retransmission(ctx, peer);
       CALL(ctx, read, &peer->session, data, data_length);
       break;
     default:
@@ -4584,7 +4621,11 @@ dtls_context_t *
 dtls_new_context(void *app_data) {
   dtls_context_t *c;
   dtls_tick_t now;
-#ifndef WITH_CONTIKI
+#if defined(_WIN32)
+  unsigned int randValue;
+  errno_t err;
+#endif
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
   FILE *urandom = fopen("/dev/urandom", "r");
   unsigned char buf[sizeof(unsigned long)];
 #endif /* WITH_CONTIKI */
@@ -4593,6 +4634,14 @@ dtls_new_context(void *app_data) {
 #ifdef WITH_CONTIKI
   /* FIXME: need something better to init PRNG here */
   dtls_prng_init(now);
+#elif defined(_WIN32)
+  err = rand_s(&randValue);
+  if (err != 0)
+  {
+    dtls_emerg("cannot initialize PRNG\n");
+    return NULL;
+  }
+  dtls_prng_init(randValue);
 #else /* WITH_CONTIKI */
   if (!urandom) {
     dtls_emerg("cannot initialize PRNG\n");
@@ -4748,7 +4797,11 @@ dtls_retransmit(dtls_context_t *context, netq_t *node) {
 
       dtls_ticks(&now);
       node->retransmit_cnt++;
-      node->t = now + (node->timeout << node->retransmit_cnt);
+      if (node->t == 1) {
+        node->t = 0;
+      } else {
+        node->t = now + (node->timeout << node->retransmit_cnt);
+      }
       netq_insert_node(context->sendqueue, node);
       
       if (node->type == DTLS_CT_HANDSHAKE) {
@@ -4789,12 +4842,40 @@ dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
 
   while (node) {
     if (dtls_session_equals(&node->peer->session, &peer->session)) {
+      node->t = 0;
+    }
+    node = list_item_next(node);
+  }
+}
+
+static void
+dtls_start_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
+  netq_t *node;
+  node = list_head(context->sendqueue);
+
+  while (node) {
+    if (dtls_session_equals(&node->peer->session, &peer->session)) {
+      node->retransmit_cnt = 0;
+      node->t = 1;
+    }
+    node = list_item_next(node);
+  }
+}
+
+static void
+dtls_clear_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
+  netq_t *node;
+  node = list_head(context->sendqueue);
+
+  while (node) {
+    if (dtls_session_equals(&node->peer->session, &peer->session)) {
       netq_t *tmp = node;
       node = list_item_next(node);
       list_remove(context->sendqueue, tmp);
       netq_node_free(tmp);
-    } else
-      node = list_item_next(node);    
+    } else {
+      node = list_item_next(node);
+    }
   }
 }
 
@@ -4804,14 +4885,16 @@ dtls_check_retransmit(dtls_context_t *context, clock_time_t *next) {
   netq_t *node = netq_head(context->sendqueue);
 
   dtls_ticks(&now);
-  while (node && node->t <= now) {
-    netq_pop_first(context->sendqueue);
-    dtls_retransmit(context, node);
-    node = netq_head(context->sendqueue);
-  }
 
-  if (next && node)
-    *next = node->t;
+  while (node) {
+    if (node->t && node->t <= now){
+      netq_pop_first(context->sendqueue);
+      dtls_retransmit(context, node);
+      node = netq_head(context->sendqueue);
+    } else {
+      node = list_item_next(node);
+    }
+  }
 }
 
 size_t
index 7cdaab2..5c23ca3 100644 (file)
@@ -368,7 +368,7 @@ void dtls_free_context(dtls_context_t *ctx);
 #define dtls_get_app_data(CTX) ((CTX)->app)
 
 /** Sets the callback handler object for @p ctx to @p h. */
-static inline void dtls_set_handler(dtls_context_t *ctx, dtls_handler_t *h) {
+INLINE_API void dtls_set_handler(dtls_context_t *ctx, dtls_handler_t *h) {
   ctx->h = h;
 }
 
@@ -454,8 +454,14 @@ void dtls_check_retransmit(dtls_context_t *context, clock_time_t *next);
 #define DTLS_CT_HANDSHAKE          22
 #define DTLS_CT_APPLICATION_DATA   23
 
+#if defined(_MSC_VER)
+#define PACKED_STRUCT __pragma(pack(1)) typedef struct
+#else
+#define PACKED_STRUCT typedef struct __attribute__((__packed__))
+#endif
+
 /** Generic header structure of the DTLS record layer. */
-typedef struct __attribute__((__packed__)) {
+PACKED_STRUCT {
   uint8 content_type;          /**< content type of the included message */
   uint16 version;              /**< Protocol version */
   uint16 epoch;                        /**< counter for cipher state changes */
@@ -479,7 +485,7 @@ typedef struct __attribute__((__packed__)) {
 #define DTLS_HT_FINISHED            20
 
 /** Header structure for the DTLS handshake protocol. */
-typedef struct __attribute__((__packed__)) {
+PACKED_STRUCT {
   uint8 msg_type; /**< Type of handshake message  (one of DTLS_HT_) */
   uint24 length;  /**< length of this message */
   uint16 message_seq;  /**< Message sequence number */
@@ -489,7 +495,7 @@ typedef struct __attribute__((__packed__)) {
 } dtls_handshake_header_t;
 
 /** Structure of the Client Hello message. */
-typedef struct __attribute__((__packed__)) {
+PACKED_STRUCT {
   uint16 version;        /**< Client version */
   uint32 gmt_random;     /**< GMT time of the random byte creation */
   unsigned char random[28];    /**< Client random bytes */
@@ -500,7 +506,7 @@ typedef struct __attribute__((__packed__)) {
 } dtls_client_hello_t;
 
 /** Structure of the Hello Verify Request. */
-typedef struct __attribute__((__packed__)) {
+PACKED_STRUCT {
   uint16 version;              /**< Server version */
   uint8 cookie_length; /**< Length of the included cookie */
   uint8 cookie[];              /**< up to 32 bytes making up the cookie */
index c6c4e39..5e0103a 100644 (file)
@@ -73,7 +73,9 @@
 #define DTLS_X509 1
 
 /* Define to 1 if you have the <arpa/inet.h> header file. */
+#ifndef _WIN32
 #define HAVE_ARPA_INET_H 1
+#endif
 
 /* Define to 1 if you have the <assert.h> header file. */
 #define HAVE_ASSERT_H 1
 #define HAVE_MEMSET 1
 
 /* Define to 1 if you have the <netdb.h> header file. */
+#ifndef _WIN32
 #define HAVE_NETDB_H 1
+#endif
 
 /* Define to 1 if you have the <netinet/in.h> header file. */
+#ifndef _WIN32
 #define HAVE_NETINET_IN_H 1
+#endif
 
 /* Define to 1 if you have the `select' function. */
 #define HAVE_SELECT 1
 #define HAVE_SYS_PARAM_H 1
 
 /* Define to 1 if you have the <sys/socket.h> header file. */
+#ifndef _WIN32
 #define HAVE_SYS_SOCKET_H 1
+#endif
 
 /* 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/time.h> header file. */
+#ifndef _WIN32
 #define HAVE_SYS_TIME_H 1
+#endif
 
 /* Define to 1 if you have the <sys/types.h> header file. */
 #define HAVE_SYS_TYPES_H 1
 /* Define to `unsigned int' if <sys/types.h> does not define. */
 
 /* #undef size_t */
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+#define ssize_t SSIZE_T
+#define snprintf vs12_snprintf
+#endif
+#if defined(_WIN32)
+#define MSG_DONTWAIT 0
+#define HAVE_WINSOCK2_H 1
+#define HAVE_WS2TCPIP_H 1
+#endif
 
 /************************************************************************/
 /* Specific Contiki platforms                                           */
index 88c292a..3018091 100644 (file)
@@ -47,12 +47,20 @@ dtls_ticks(dtls_tick_t *t) {
 }
 
 #else /* WITH_CONTIKI */
+#ifdef _WIN32
+#include <windows.h>
+#endif
 
 time_t dtls_clock_offset;
 
 void
 dtls_clock_init(void) {
+#ifdef _WIN32
+  /* Use clock offset in milliseconds */
+  dtls_clock_offset = GetTickCount();
+#else
 #ifdef HAVE_TIME_H
+  /* Use clock offset in seconds */
   dtls_clock_offset = time(NULL);
 #else
 #  ifdef __GNUC__
@@ -62,9 +70,13 @@ dtls_clock_init(void) {
 #  endif
   dtls_clock_offset = 0;
 #endif
+#endif
 }
 
 void dtls_ticks(dtls_tick_t *t) {
+#ifdef _WIN32
+  *t = ((GetTickCount() - dtls_clock_offset) * DTLS_TICKS_PER_SECOND / 1000);
+#else
 #ifdef HAVE_SYS_TIME_H
   struct timeval tv;
   gettimeofday(&tv, NULL);
@@ -73,6 +85,7 @@ void dtls_ticks(dtls_tick_t *t) {
 #else
 #error "clock not implemented"
 #endif
+#endif
 }
 
 #endif /* WITH_CONTIKI */
index 82ff062..6541b1c 100644 (file)
@@ -32,7 +32,9 @@
 #define _DTLS_DTLS_TIME_H_
 
 #include <stdint.h>
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
+#endif
 
 #include "tinydtls.h"
 
index 75877fd..8f947e7 100644 (file)
@@ -115,7 +115,7 @@ typedef enum {
 /**
  * XORs \p n bytes byte-by-byte starting at \p y to the memory area
  * starting at \p x. */
-static inline void
+INLINE_API void
 memxor(unsigned char *x, const unsigned char *y, size_t n) {
   while(n--) {
     *x ^= *y;
@@ -133,7 +133,7 @@ memxor(unsigned char *x, const unsigned char *y, size_t n) {
  * \param len Number of bytes to compare.
  * \return \c 1 if \p a and \p b are equal, \c 0 otherwise.
  */
-static inline int
+INLINE_API int
 equals(unsigned char *a, unsigned char *b, size_t len) {
   int result = 1;
   while (len--) {
@@ -145,7 +145,7 @@ equals(unsigned char *a, unsigned char *b, size_t len) {
 #ifdef HAVE_FLS
 #define dtls_fls(i) fls(i)
 #else
-static inline int
+INLINE_API int
 dtls_fls(unsigned int i) {
   int n;
   for (n = 0; i; n++)
index 0a9b8f7..571a59a 100644 (file)
 #ifndef WITH_CONTIKI
 #include <stdlib.h>
 
-static inline dtls_hmac_context_t *
+INLINE_API dtls_hmac_context_t *
 dtls_hmac_context_new() {
   return (dtls_hmac_context_t *)malloc(sizeof(dtls_hmac_context_t));
 }
 
-static inline void
+INLINE_API void
 dtls_hmac_context_free(dtls_hmac_context_t *ctx) {
   free(ctx);
 }
@@ -56,12 +56,12 @@ dtls_hmac_context_free(dtls_hmac_context_t *ctx) {
 #include "memb.h"
 MEMB(hmac_context_storage, dtls_hmac_context_t, DTLS_HASH_MAX);
 
-static inline dtls_hmac_context_t *
+INLINE_API dtls_hmac_context_t *
 dtls_hmac_context_new() {
   return (dtls_hmac_context_t *)memb_alloc(&hmac_context_storage);
 }
 
-static inline void
+INLINE_API void
 dtls_hmac_context_free(dtls_hmac_context_t *ctx) {
   memb_free(&hmac_context_storage, ctx);
 }
index afdfaea..e4046a7 100644 (file)
  *  see http://www.aarongifford.com/ */
 #include "sha2/sha2.h"
 
-typedef DTLS_SHA256_CTX dtls_hash_ctx;
+typedef dtls_sha256_ctx dtls_hash_ctx;
 typedef dtls_hash_ctx *dtls_hash_t;
-#define DTLS_HASH_CTX_SIZE sizeof(DTLS_SHA256_CTX)
+#define DTLS_HASH_CTX_SIZE sizeof(dtls_sha256_ctx)
 
-static inline void
+INLINE_API void
 dtls_hash_init(dtls_hash_t ctx) {
-  DTLS_SHA256_Init((DTLS_SHA256_CTX *)ctx);
+  dtls_sha256_init((dtls_sha256_ctx *)ctx);
 }
 
-static inline void 
+INLINE_API void 
 dtls_hash_update(dtls_hash_t ctx, const unsigned char *input, size_t len) {
-  DTLS_SHA256_Update((DTLS_SHA256_CTX *)ctx, input, len);
+  dtls_sha256_update((dtls_sha256_ctx *)ctx, input, len);
 }
 
-static inline size_t
+INLINE_API size_t
 dtls_hash_finalize(unsigned char *buf, dtls_hash_t ctx) {
-  DTLS_SHA256_Final(buf, (DTLS_SHA256_CTX *)ctx);
+  dtls_sha256_final(buf, (dtls_sha256_ctx *)ctx);
   return DTLS_SHA256_DIGEST_LENGTH;
 }
 #endif /* WITH_SHA256 */
 
 #ifndef WITH_CONTIKI
-static inline void dtls_hmac_storage_init()
+INLINE_API void dtls_hmac_storage_init()
 { }
 #else
 void dtls_hmac_storage_init();
index 0a10a50..8589858 100644 (file)
 #ifndef WITH_CONTIKI
 #include <stdlib.h>
 
-static inline netq_t *
+INLINE_API netq_t *
 netq_malloc_node(size_t size) {
   return (netq_t *)malloc(sizeof(netq_t) + size);
 }
 
-static inline void
+INLINE_API void
 netq_free_node(netq_t *node) {
   free(node);
 }
@@ -41,12 +41,12 @@ netq_free_node(netq_t *node) {
 
 MEMB(netq_storage, netq_t, NETQ_MAXCNT);
 
-static inline netq_t *
+INLINE_API netq_t *
 netq_malloc_node(size_t size) {
   return (netq_t *)memb_alloc(&netq_storage);
 }
 
-static inline void
+INLINE_API void
 netq_free_node(netq_t *node) {
   memb_free(&netq_storage, node);
 }
index fea7511..c3db339 100644 (file)
@@ -55,7 +55,7 @@ typedef struct netq_t {
 } netq_t;
 
 #ifndef WITH_CONTIKI
-static inline void netq_init()
+INLINE_API void netq_init()
 { }
 #else
 void netq_init();
index e319f5b..5af0c4c 100644 (file)
 #endif
 
 /* this one is for consistency... */
-static inline int dtls_int_to_uint8(unsigned char *field, uint8_t value)
+INLINE_API int dtls_int_to_uint8(unsigned char *field, uint8_t value)
 {
   field[0] = value & 0xff;
   return 1;
 }
 
-static inline int dtls_int_to_uint16(unsigned char *field, uint16_t value)
+INLINE_API int dtls_int_to_uint16(unsigned char *field, uint16_t value)
 {
   field[0] = (value >> 8) & 0xff;
   field[1] = value & 0xff;
   return 2;
 }
 
-static inline int dtls_int_to_uint24(unsigned char *field, uint32_t value)
+INLINE_API int dtls_int_to_uint24(unsigned char *field, uint32_t value)
 {
   field[0] = (value >> 16) & 0xff;
   field[1] = (value >> 8) & 0xff;
@@ -58,7 +58,7 @@ static inline int dtls_int_to_uint24(unsigned char *field, uint32_t value)
   return 3;
 }
 
-static inline int dtls_int_to_uint32(unsigned char *field, uint32_t value)
+INLINE_API int dtls_int_to_uint32(unsigned char *field, uint32_t value)
 {
   field[0] = (value >> 24) & 0xff;
   field[1] = (value >> 16) & 0xff;
@@ -67,7 +67,7 @@ static inline int dtls_int_to_uint32(unsigned char *field, uint32_t value)
   return 4;
 }
 
-static inline int dtls_int_to_uint48(unsigned char *field, uint64_t value)
+INLINE_API int dtls_int_to_uint48(unsigned char *field, uint64_t value)
 {
   field[0] = (value >> 40) & 0xff;
   field[1] = (value >> 32) & 0xff;
@@ -78,7 +78,7 @@ static inline int dtls_int_to_uint48(unsigned char *field, uint64_t value)
   return 6;
 }
 
-static inline int dtls_int_to_uint64(unsigned char *field, uint64_t value)
+INLINE_API int dtls_int_to_uint64(unsigned char *field, uint64_t value)
 {
   field[0] = (value >> 56) & 0xff;
   field[1] = (value >> 48) & 0xff;
@@ -91,25 +91,25 @@ static inline int dtls_int_to_uint64(unsigned char *field, uint64_t value)
   return 8;
 }
 
-static inline uint8_t dtls_uint8_to_int(const unsigned char *field)
+INLINE_API uint8_t dtls_uint8_to_int(const unsigned char *field)
 {
   return (uint8_t)field[0];
 }
 
-static inline uint16_t dtls_uint16_to_int(const unsigned char *field)
+INLINE_API uint16_t dtls_uint16_to_int(const unsigned char *field)
 {
   return ((uint16_t)field[0] << 8)
         | (uint16_t)field[1];
 }
 
-static inline uint32_t dtls_uint24_to_int(const unsigned char *field)
+INLINE_API uint32_t dtls_uint24_to_int(const unsigned char *field)
 {
   return ((uint32_t)field[0] << 16)
         | ((uint32_t)field[1] << 8)
         | (uint32_t)field[2];
 }
 
-static inline uint32_t dtls_uint32_to_int(const unsigned char *field)
+INLINE_API uint32_t dtls_uint32_to_int(const unsigned char *field)
 {
   return ((uint32_t)field[0] << 24)
         | ((uint32_t)field[1] << 16)
@@ -117,7 +117,7 @@ static inline uint32_t dtls_uint32_to_int(const unsigned char *field)
         | (uint32_t)field[3];
 }
 
-static inline uint64_t dtls_uint48_to_int(const unsigned char *field)
+INLINE_API uint64_t dtls_uint48_to_int(const unsigned char *field)
 {
   return ((uint64_t)field[0] << 40)
         | ((uint64_t)field[1] << 32)
@@ -127,7 +127,7 @@ static inline uint64_t dtls_uint48_to_int(const unsigned char *field)
         | (uint64_t)field[5];
 }
 
-static inline uint64_t dtls_uint64_to_int(const unsigned char *field)
+INLINE_API uint64_t dtls_uint64_to_int(const unsigned char *field)
 {
   return ((uint64_t)field[0] << 56)
         | ((uint64_t)field[1] << 48)
index 8f2876c..109a612 100644 (file)
@@ -32,7 +32,7 @@ void peer_init()
 {
 }
 
-static inline dtls_peer_t *
+INLINE_API dtls_peer_t *
 dtls_malloc_peer() {
   return (dtls_peer_t *)malloc(sizeof(dtls_peer_t));
 }
@@ -54,7 +54,7 @@ peer_init() {
   memb_init(&peer_storage);
 }
 
-static inline dtls_peer_t *
+INLINE_API dtls_peer_t *
 dtls_malloc_peer() {
   return memb_alloc(&peer_storage);
 }
index af7c205..41fd943 100644 (file)
@@ -65,7 +65,7 @@ typedef struct dtls_peer_t {
   dtls_handshake_parameters_t *handshake_params;
 } dtls_peer_t;
 
-static inline dtls_security_parameters_t *dtls_security_params_epoch(dtls_peer_t *peer, uint16_t epoch)
+INLINE_API dtls_security_parameters_t *dtls_security_params_epoch(dtls_peer_t *peer, uint16_t epoch)
 {
   if (peer->security_params[0] && peer->security_params[0]->epoch == epoch) {
     return peer->security_params[0];
@@ -76,12 +76,12 @@ static inline dtls_security_parameters_t *dtls_security_params_epoch(dtls_peer_t
   }
 }
 
-static inline dtls_security_parameters_t *dtls_security_params(dtls_peer_t *peer)
+INLINE_API dtls_security_parameters_t *dtls_security_params(dtls_peer_t *peer)
 {
   return peer->security_params[0];
 }
 
-static inline dtls_security_parameters_t *dtls_security_params_next(dtls_peer_t *peer)
+INLINE_API dtls_security_parameters_t *dtls_security_params_next(dtls_peer_t *peer)
 {
   if (peer->security_params[1])
     dtls_security_free(peer->security_params[1]);
@@ -94,7 +94,7 @@ static inline dtls_security_parameters_t *dtls_security_params_next(dtls_peer_t
   return peer->security_params[1];
 }
 
-static inline void dtls_security_params_free_other(dtls_peer_t *peer)
+INLINE_API void dtls_security_params_free_other(dtls_peer_t *peer)
 {
   dtls_security_parameters_t * security0 = peer->security_params[0];
   dtls_security_parameters_t * security1 = peer->security_params[1];
@@ -106,7 +106,7 @@ static inline void dtls_security_params_free_other(dtls_peer_t *peer)
   peer->security_params[1] = NULL;
 }
 
-static inline void dtls_security_params_switch(dtls_peer_t *peer)
+INLINE_API void dtls_security_params_switch(dtls_peer_t *peer)
 {
   dtls_security_parameters_t * security = peer->security_params[1];
 
@@ -133,7 +133,7 @@ dtls_peer_t *dtls_new_peer(const session_t *session);
 void dtls_free_peer(dtls_peer_t *peer);
 
 /** Returns the current state of @p peer. */
-static inline dtls_state_t dtls_peer_state(const dtls_peer_t *peer) {
+INLINE_API dtls_state_t dtls_peer_state(const dtls_peer_t *peer) {
   return peer->state;
 }
 
@@ -141,7 +141,7 @@ static inline dtls_state_t dtls_peer_state(const dtls_peer_t *peer) {
  * Checks if given @p peer is connected. This function returns
  * @c 1 if connected, or @c 0 otherwise.
  */
-static inline int dtls_peer_is_connected(const dtls_peer_t *peer) {
+INLINE_API int dtls_peer_is_connected(const dtls_peer_t *peer) {
   return peer->state == DTLS_STATE_CONNECTED;
 }
 
index 48c1f95..daf956b 100644 (file)
  * implementation for prng().  You might want to change prng() to use
  * a better PRNG on your specific platform.
  */
-static inline int
+INLINE_API int
 dtls_prng(unsigned char *buf, size_t len) {
   while (len--)
     *buf++ = rand() & 0xFF;
   return 1;
 }
 
-static inline void
+INLINE_API void
 dtls_prng_init(unsigned short seed) {
        srand(seed);
 }
@@ -45,7 +45,7 @@ dtls_prng_init(unsigned short seed) {
 #include "random.h"
 
 #ifdef HAVE_PRNG
-static inline int
+INLINE_API int
 dtls_prng(unsigned char *buf, size_t len)
 {
        return contiki_prng_impl(buf, len);
@@ -56,7 +56,7 @@ dtls_prng(unsigned char *buf, size_t len)
  * implementation for prng().  You might want to change prng() to use
  * a better PRNG on your specific platform.
  */
-static inline int
+INLINE_API int
 dtls_prng(unsigned char *buf, size_t len) {
   unsigned short v = random_rand();
   while (len > sizeof(v)) {
@@ -71,7 +71,7 @@ dtls_prng(unsigned char *buf, size_t len) {
 }
 #endif /* HAVE_PRNG */
 
-static inline void
+INLINE_API void
 dtls_prng_init(unsigned short seed) {
        random_init(seed);
 }
index 9acf565..51155b0 100644 (file)
@@ -44,7 +44,7 @@
 
 #else /* WITH_CONTIKI */
 
-static inline int 
+INLINE_API int 
 _dtls_address_equals_impl(const session_t *a,
                          const session_t *b) {
   if (a->ifindex != b->ifindex ||
index 61b5661..bd848f2 100644 (file)
@@ -28,6 +28,7 @@
 
 #include <string.h>
 
+#include "dtls_config.h"
 #include "tinydtls.h"
 #include "global.h"
 
@@ -42,9 +43,22 @@ typedef struct {
 
 #else /* WITH_CONTIKI */
 
+#ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
 #include <netinet/in.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
 #include <arpa/inet.h>
+#endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+#include <stdint.h>
 
 typedef struct {
   socklen_t size;              /**< size of addr */
index 4d729e7..c42c993 100644 (file)
@@ -245,9 +245,9 @@ typedef u_int64_t sha2_word64;      /* Exactly 8 bytes */
  * library -- they are intended for private internal visibility/use
  * only.
  */
-void DTLS_SHA512_Last(DTLS_SHA512_CTX*);
-void DTLS_SHA256_Transform(DTLS_SHA256_CTX*, const sha2_word32*);
-void DTLS_SHA512_Transform(DTLS_SHA512_CTX*, const sha2_word64*);
+void dtls_sha512_last(dtls_sha512_ctx*);
+void dtls_sha256_transform(dtls_sha256_ctx*, const sha2_word32*);
+void dtls_sha512_transform(dtls_sha512_ctx*, const sha2_word64*);
 
 #ifdef WITH_SHA256
 /*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/
@@ -367,8 +367,8 @@ static const char *sha2_hex_digits = "0123456789abcdef";
 
 /*** SHA-256: *********************************************************/
 #ifdef WITH_SHA256
-void DTLS_SHA256_Init(DTLS_SHA256_CTX* context) {
-       if (context == (DTLS_SHA256_CTX*)0) {
+void dtls_sha256_init(dtls_sha256_ctx* context) {
+       if (context == (dtls_sha256_ctx*)0) {
                return;
        }
        MEMCPY_BCOPY(context->state, sha256_initial_hash_value, DTLS_SHA256_DIGEST_LENGTH);
@@ -413,7 +413,7 @@ void DTLS_SHA256_Init(DTLS_SHA256_CTX* context) {
        (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
        j++
 
-void DTLS_SHA256_Transform(DTLS_SHA256_CTX* context, const sha2_word32* data) {
+void dtls_sha256_transform(dtls_sha256_ctx* context, const sha2_word32* data) {
        sha2_word32     a, b, c, d, e, f, g, h, s0, s1;
        sha2_word32     T1, *W256;
        int             j;
@@ -471,7 +471,7 @@ void DTLS_SHA256_Transform(DTLS_SHA256_CTX* context, const sha2_word32* data) {
 
 #else /* SHA2_UNROLL_TRANSFORM */
 
-void DTLS_SHA256_Transform(DTLS_SHA256_CTX* context, const sha2_word32* data) {
+void dtls_sha256_transform(dtls_sha256_ctx* context, const sha2_word32* data) {
        sha2_word32     a, b, c, d, e, f, g, h, s0, s1;
        sha2_word32     T1, T2, *W256;
        int             j;
@@ -551,7 +551,7 @@ void DTLS_SHA256_Transform(DTLS_SHA256_CTX* context, const sha2_word32* data) {
 
 #endif /* SHA2_UNROLL_TRANSFORM */
 
-void DTLS_SHA256_Update(DTLS_SHA256_CTX* context, const sha2_byte *data, size_t len) {
+void dtls_sha256_update(dtls_sha256_ctx* context, const sha2_byte *data, size_t len) {
        unsigned int    freespace, usedspace;
 
        if (len == 0) {
@@ -560,7 +560,7 @@ void DTLS_SHA256_Update(DTLS_SHA256_CTX* context, const sha2_byte *data, size_t
        }
 
        /* Sanity check: */
-       assert(context != (DTLS_SHA256_CTX*)0 && data != (sha2_byte*)0);
+       assert(context != (dtls_sha256_ctx*)0 && data != (sha2_byte*)0);
 
        usedspace = (context->bitcount >> 3) % DTLS_SHA256_BLOCK_LENGTH;
        if (usedspace > 0) {
@@ -573,7 +573,7 @@ void DTLS_SHA256_Update(DTLS_SHA256_CTX* context, const sha2_byte *data, size_t
                        context->bitcount += freespace << 3;
                        len -= freespace;
                        data += freespace;
-                       DTLS_SHA256_Transform(context, (sha2_word32*)context->buffer);
+                       dtls_sha256_transform(context, (sha2_word32*)context->buffer);
                } else {
                        /* The buffer is not yet full */
                        MEMCPY_BCOPY(&context->buffer[usedspace], data, len);
@@ -585,7 +585,7 @@ void DTLS_SHA256_Update(DTLS_SHA256_CTX* context, const sha2_byte *data, size_t
        }
        while (len >= DTLS_SHA256_BLOCK_LENGTH) {
                /* Process as many complete blocks as we can */
-               DTLS_SHA256_Transform(context, (sha2_word32*)data);
+               dtls_sha256_transform(context, (sha2_word32*)data);
                context->bitcount += DTLS_SHA256_BLOCK_LENGTH << 3;
                len -= DTLS_SHA256_BLOCK_LENGTH;
                data += DTLS_SHA256_BLOCK_LENGTH;
@@ -599,12 +599,12 @@ void DTLS_SHA256_Update(DTLS_SHA256_CTX* context, const sha2_byte *data, size_t
        usedspace = freespace = 0;
 }
 
-void DTLS_SHA256_Final(sha2_byte digest[], DTLS_SHA256_CTX* context) {
+void dtls_sha256_final(sha2_byte digest[], dtls_sha256_ctx* context) {
        sha2_word32     *d = (sha2_word32*)digest;
        unsigned int    usedspace;
 
        /* Sanity check: */
-       assert(context != (DTLS_SHA256_CTX*)0);
+       assert(context != (dtls_sha256_ctx*)0);
 
        /* If no digest buffer is passed, we don't bother doing this: */
        if (digest != (sha2_byte*)0) {
@@ -625,7 +625,7 @@ void DTLS_SHA256_Final(sha2_byte digest[], DTLS_SHA256_CTX* context) {
                                        MEMSET_BZERO(&context->buffer[usedspace], DTLS_SHA256_BLOCK_LENGTH - usedspace);
                                }
                                /* Do second-to-last transform: */
-                               DTLS_SHA256_Transform(context, (sha2_word32*)context->buffer);
+                               dtls_sha256_transform(context, (sha2_word32*)context->buffer);
 
                                /* And set-up for the last transform: */
                                MEMSET_BZERO(context->buffer, DTLS_SHA256_SHORT_BLOCK_LENGTH);
@@ -641,7 +641,7 @@ void DTLS_SHA256_Final(sha2_byte digest[], DTLS_SHA256_CTX* context) {
                *(sha2_word64*)&context->buffer[DTLS_SHA256_SHORT_BLOCK_LENGTH] = context->bitcount;
 
                /* Final transform: */
-               DTLS_SHA256_Transform(context, (sha2_word32*)context->buffer);
+               dtls_sha256_transform(context, (sha2_word32*)context->buffer);
 
 #if BYTE_ORDER == LITTLE_ENDIAN
                {
@@ -662,15 +662,15 @@ void DTLS_SHA256_Final(sha2_byte digest[], DTLS_SHA256_CTX* context) {
        usedspace = 0;
 }
 
-char *DTLS_SHA256_End(DTLS_SHA256_CTX* context, char buffer[]) {
+char *dtls_sha256_end(dtls_sha256_ctx* context, char buffer[]) {
        sha2_byte       digest[DTLS_SHA256_DIGEST_LENGTH], *d = digest;
        int             i;
 
        /* Sanity check: */
-       assert(context != (DTLS_SHA256_CTX*)0);
+       assert(context != (dtls_sha256_ctx*)0);
 
        if (buffer != (char*)0) {
-               DTLS_SHA256_Final(digest, context);
+               dtls_sha256_final(digest, context);
 
                for (i = 0; i < DTLS_SHA256_DIGEST_LENGTH; i++) {
                        *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
@@ -685,19 +685,19 @@ char *DTLS_SHA256_End(DTLS_SHA256_CTX* context, char buffer[]) {
        return buffer;
 }
 
-char* DTLS_SHA256_Data(const sha2_byte* data, size_t len, char digest[DTLS_SHA256_DIGEST_STRING_LENGTH]) {
-       DTLS_SHA256_CTX context;
+char* dtls_sha256_data(const sha2_byte* data, size_t len, char digest[DTLS_SHA256_DIGEST_STRING_LENGTH]) {
+       dtls_sha256_ctx context;
 
-       DTLS_SHA256_Init(&context);
-       DTLS_SHA256_Update(&context, data, len);
-       return DTLS_SHA256_End(&context, digest);
+       dtls_sha256_init(&context);
+       dtls_sha256_update(&context, data, len);
+       return dtls_sha256_end(&context, digest);
 }
 #endif
 
 /*** SHA-512: *********************************************************/
 #ifdef WITH_SHA512
-void DTLS_SHA512_Init(DTLS_SHA512_CTX* context) {
-       if (context == (DTLS_SHA512_CTX*)0) {
+void dtls_sha512_init(dtls_sha512_ctx* context) {
+       if (context == (dtls_sha512_ctx*)0) {
                return;
        }
        MEMCPY_BCOPY(context->state, sha512_initial_hash_value, DTLS_SHA512_DIGEST_LENGTH);
@@ -741,7 +741,7 @@ void DTLS_SHA512_Init(DTLS_SHA512_CTX* context) {
        (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
        j++
 
-void DTLS_SHA512_Transform(DTLS_SHA512_CTX* context, const sha2_word64* data) {
+void dtls_sha512_transform(dtls_sha512_ctx* context, const sha2_word64* data) {
        sha2_word64     a, b, c, d, e, f, g, h, s0, s1;
        sha2_word64     T1, *W512 = (sha2_word64*)context->buffer;
        int             j;
@@ -796,7 +796,7 @@ void DTLS_SHA512_Transform(DTLS_SHA512_CTX* context, const sha2_word64* data) {
 
 #else /* SHA2_UNROLL_TRANSFORM */
 
-void DTLS_SHA512_Transform(DTLS_SHA512_CTX* context, const sha2_word64* data) {
+void dtls_sha512_transform(dtls_sha512_ctx* context, const sha2_word64* data) {
        sha2_word64     a, b, c, d, e, f, g, h, s0, s1;
        sha2_word64     T1, T2, *W512 = (sha2_word64*)context->buffer;
        int             j;
@@ -874,7 +874,7 @@ void DTLS_SHA512_Transform(DTLS_SHA512_CTX* context, const sha2_word64* data) {
 
 #endif /* SHA2_UNROLL_TRANSFORM */
 
-void DTLS_SHA512_Update(DTLS_SHA512_CTX* context, const sha2_byte *data, size_t len) {
+void dtls_sha512_update(dtls_sha512_ctx* context, const sha2_byte *data, size_t len) {
        unsigned int    freespace, usedspace;
 
        if (len == 0) {
@@ -883,7 +883,7 @@ void DTLS_SHA512_Update(DTLS_SHA512_CTX* context, const sha2_byte *data, size_t
        }
 
        /* Sanity check: */
-       assert(context != (DTLS_SHA512_CTX*)0 && data != (sha2_byte*)0);
+       assert(context != (dtls_sha512_ctx*)0 && data != (sha2_byte*)0);
 
        usedspace = (context->bitcount[0] >> 3) % DTLS_SHA512_BLOCK_LENGTH;
        if (usedspace > 0) {
@@ -896,7 +896,7 @@ void DTLS_SHA512_Update(DTLS_SHA512_CTX* context, const sha2_byte *data, size_t
                        ADDINC128(context->bitcount, freespace << 3);
                        len -= freespace;
                        data += freespace;
-                       DTLS_SHA512_Transform(context, (sha2_word64*)context->buffer);
+                       dtls_sha512_transform(context, (sha2_word64*)context->buffer);
                } else {
                        /* The buffer is not yet full */
                        MEMCPY_BCOPY(&context->buffer[usedspace], data, len);
@@ -908,7 +908,7 @@ void DTLS_SHA512_Update(DTLS_SHA512_CTX* context, const sha2_byte *data, size_t
        }
        while (len >= DTLS_SHA512_BLOCK_LENGTH) {
                /* Process as many complete blocks as we can */
-               DTLS_SHA512_Transform(context, (sha2_word64*)data);
+               dtls_sha512_transform(context, (sha2_word64*)data);
                ADDINC128(context->bitcount, DTLS_SHA512_BLOCK_LENGTH << 3);
                len -= DTLS_SHA512_BLOCK_LENGTH;
                data += DTLS_SHA512_BLOCK_LENGTH;
@@ -922,7 +922,7 @@ void DTLS_SHA512_Update(DTLS_SHA512_CTX* context, const sha2_byte *data, size_t
        usedspace = freespace = 0;
 }
 
-void DTLS_SHA512_Last(DTLS_SHA512_CTX* context) {
+void dtls_sha512_last(dtls_sha512_ctx* context) {
        unsigned int    usedspace;
 
        usedspace = (context->bitcount[0] >> 3) % DTLS_SHA512_BLOCK_LENGTH;
@@ -943,7 +943,7 @@ void DTLS_SHA512_Last(DTLS_SHA512_CTX* context) {
                                MEMSET_BZERO(&context->buffer[usedspace], DTLS_SHA512_BLOCK_LENGTH - usedspace);
                        }
                        /* Do second-to-last transform: */
-                       DTLS_SHA512_Transform(context, (sha2_word64*)context->buffer);
+                       dtls_sha512_transform(context, (sha2_word64*)context->buffer);
 
                        /* And set-up for the last transform: */
                        MEMSET_BZERO(context->buffer, DTLS_SHA512_BLOCK_LENGTH - 2);
@@ -960,18 +960,18 @@ void DTLS_SHA512_Last(DTLS_SHA512_CTX* context) {
        *(sha2_word64*)&context->buffer[DTLS_SHA512_SHORT_BLOCK_LENGTH+8] = context->bitcount[0];
 
        /* Final transform: */
-       DTLS_SHA512_Transform(context, (sha2_word64*)context->buffer);
+       dtls_sha512_transform(context, (sha2_word64*)context->buffer);
 }
 
-void DTLS_SHA512_Final(sha2_byte digest[], DTLS_SHA512_CTX* context) {
+void dtls_sha512_final(sha2_byte digest[], dtls_sha512_ctx* context) {
        sha2_word64     *d = (sha2_word64*)digest;
 
        /* Sanity check: */
-       assert(context != (DTLS_SHA512_CTX*)0);
+       assert(context != (dtls_sha512_ctx*)0);
 
        /* If no digest buffer is passed, we don't bother doing this: */
        if (digest != (sha2_byte*)0) {
-               DTLS_SHA512_Last(context);
+               dtls_sha512_last(context);
 
                /* Save the hash data for output: */
 #if BYTE_ORDER == LITTLE_ENDIAN
@@ -992,15 +992,15 @@ void DTLS_SHA512_Final(sha2_byte digest[], DTLS_SHA512_CTX* context) {
        MEMSET_BZERO(context, sizeof(context));
 }
 
-char *DTLS_SHA512_End(DTLS_SHA512_CTX* context, char buffer[]) {
+char *dtls_sha512_end(dtls_sha512_ctx* context, char buffer[]) {
        sha2_byte       digest[DTLS_SHA512_DIGEST_LENGTH], *d = digest;
        int             i;
 
        /* Sanity check: */
-       assert(context != (DTLS_SHA512_CTX*)0);
+       assert(context != (dtls_sha512_ctx*)0);
 
        if (buffer != (char*)0) {
-               DTLS_SHA512_Final(digest, context);
+               dtls_sha512_final(digest, context);
 
                for (i = 0; i < DTLS_SHA512_DIGEST_LENGTH; i++) {
                        *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
@@ -1015,19 +1015,19 @@ char *DTLS_SHA512_End(DTLS_SHA512_CTX* context, char buffer[]) {
        return buffer;
 }
 
-char* DTLS_SHA512_Data(const sha2_byte* data, size_t len, char digest[DTLS_SHA512_DIGEST_STRING_LENGTH]) {
-       DTLS_SHA512_CTX context;
+char* dtls_sha512_data(const sha2_byte* data, size_t len, char digest[DTLS_SHA512_DIGEST_STRING_LENGTH]) {
+       dtls_sha512_ctx context;
 
-       DTLS_SHA512_Init(&context);
-       DTLS_SHA512_Update(&context, data, len);
-       return DTLS_SHA512_End(&context, digest);
+       dtls_sha512_init(&context);
+       dtls_sha512_update(&context, data, len);
+       return dtls_sha512_end(&context, digest);
 }
 #endif
 
 /*** SHA-384: *********************************************************/
 #ifdef WITH_SHA384
-void DTLS_SHA384_Init(DTLS_SHA384_CTX* context) {
-       if (context == (DTLS_SHA384_CTX*)0) {
+void dtls_sha384_init(dtls_sha384_ctx* context) {
+       if (context == (dtls_sha384_ctx*)0) {
                return;
        }
        MEMCPY_BCOPY(context->state, sha384_initial_hash_value, DTLS_SHA512_DIGEST_LENGTH);
@@ -1035,19 +1035,19 @@ void DTLS_SHA384_Init(DTLS_SHA384_CTX* context) {
        context->bitcount[0] = context->bitcount[1] = 0;
 }
 
-void DTLS_SHA384_Update(DTLS_SHA384_CTX* context, const sha2_byte* data, size_t len) {
-       DTLS_SHA512_Update((DTLS_SHA512_CTX*)context, data, len);
+void dtls_sha384_update(dtls_sha384_ctx* context, const sha2_byte* data, size_t len) {
+       dtls_sha512_update((dtls_sha512_ctx*)context, data, len);
 }
 
-void DTLS_SHA384_Final(sha2_byte digest[], DTLS_SHA384_CTX* context) {
+void dtls_sha384_final(sha2_byte digest[], dtls_sha384_ctx* context) {
        sha2_word64     *d = (sha2_word64*)digest;
 
        /* Sanity check: */
-       assert(context != (DTLS_SHA384_CTX*)0);
+       assert(context != (dtls_sha384_ctx*)0);
 
        /* If no digest buffer is passed, we don't bother doing this: */
        if (digest != (sha2_byte*)0) {
-               DTLS_SHA512_Last((DTLS_SHA512_CTX*)context);
+               dtls_sha512_last((dtls_sha512_ctx*)context);
 
                /* Save the hash data for output: */
 #if BYTE_ORDER == LITTLE_ENDIAN
@@ -1068,15 +1068,15 @@ void DTLS_SHA384_Final(sha2_byte digest[], DTLS_SHA384_CTX* context) {
        MEMSET_BZERO(context, sizeof(context));
 }
 
-char *DTLS_SHA384_End(DTLS_SHA384_CTX* context, char buffer[]) {
+char *dtls_sha384_end(dtls_sha384_ctx* context, char buffer[]) {
        sha2_byte       digest[DTLS_SHA384_DIGEST_LENGTH], *d = digest;
        int             i;
 
        /* Sanity check: */
-       assert(context != (DTLS_SHA384_CTX*)0);
+       assert(context != (dtls_sha384_ctx*)0);
 
        if (buffer != (char*)0) {
-               DTLS_SHA384_Final(digest, context);
+               dtls_sha384_final(digest, context);
 
                for (i = 0; i < DTLS_SHA384_DIGEST_LENGTH; i++) {
                        *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
@@ -1091,11 +1091,11 @@ char *DTLS_SHA384_End(DTLS_SHA384_CTX* context, char buffer[]) {
        return buffer;
 }
 
-char* DTLS_SHA384_Data(const sha2_byte* data, size_t len, char digest[DTLS_SHA384_DIGEST_STRING_LENGTH]) {
-       DTLS_SHA384_CTX context;
+char* dtls_sha384_data(const sha2_byte* data, size_t len, char digest[DTLS_SHA384_DIGEST_STRING_LENGTH]) {
+       dtls_sha384_ctx context;
 
-       DTLS_SHA384_Init(&context);
-       DTLS_SHA384_Update(&context, data, len);
-       return DTLS_SHA384_End(&context, digest);
+       dtls_sha384_init(&context);
+       dtls_sha384_update(&context, data, len);
+       return dtls_sha384_end(&context, digest);
 }
 #endif
index e6eecc4..c56b42a 100644 (file)
@@ -94,33 +94,33 @@ typedef unsigned long long u_int64_t;       /* 8-bytes (64-bits) */
  */
 #ifdef SHA2_USE_INTTYPES_H
 
-typedef struct _DTLS_SHA256_CTX {
+typedef struct _dtls_sha256_ctx {
        uint32_t        state[8];
        uint64_t        bitcount;
        uint8_t buffer[DTLS_SHA256_BLOCK_LENGTH];
-} DTLS_SHA256_CTX;
-typedef struct _DTLS_SHA512_CTX {
+} dtls_sha256_ctx;
+typedef struct _dtls_sha512_ctx {
        uint64_t        state[8];
        uint64_t        bitcount[2];
        uint8_t buffer[DTLS_SHA512_BLOCK_LENGTH];
-} DTLS_SHA512_CTX;
+} dtls_sha512_ctx;
 
 #else /* SHA2_USE_INTTYPES_H */
 
-typedef struct _DTLS_SHA256_CTX {
+typedef struct _dtls_sha256_ctx {
        u_int32_t       state[8];
        u_int64_t       bitcount;
        u_int8_t        buffer[DTLS_SHA256_BLOCK_LENGTH];
-} DTLS_SHA256_CTX;
-typedef struct _DTLS_SHA512_CTX {
+} dtls_sha256_ctx;
+typedef struct _dtls_sha512_ctx {
        u_int64_t       state[8];
        u_int64_t       bitcount[2];
        u_int8_t        buffer[DTLS_SHA512_BLOCK_LENGTH];
-} DTLS_SHA512_CTX;
+} dtls_sha512_ctx;
 
 #endif /* SHA2_USE_INTTYPES_H */
 
-typedef DTLS_SHA512_CTX DTLS_SHA384_CTX;
+typedef dtls_sha512_ctx dtls_sha384_ctx;
 
 
 /*** SHA-256/384/512 Function Prototypes ******************************/
@@ -128,53 +128,53 @@ typedef DTLS_SHA512_CTX DTLS_SHA384_CTX;
 #ifdef SHA2_USE_INTTYPES_H
 
 #ifdef WITH_SHA256
-void DTLS_SHA256_Init(DTLS_SHA256_CTX *);
-void DTLS_SHA256_Update(DTLS_SHA256_CTX*, const uint8_t*, size_t);
-void DTLS_SHA256_Final(uint8_t[DTLS_SHA256_DIGEST_LENGTH], DTLS_SHA256_CTX*);
-char* DTLS_SHA256_End(DTLS_SHA256_CTX*, char[DTLS_SHA256_DIGEST_STRING_LENGTH]);
-char* DTLS_SHA256_Data(const uint8_t*, size_t, char[DTLS_SHA256_DIGEST_STRING_LENGTH]);
+void dtls_sha256_init(dtls_sha256_ctx *);
+void dtls_sha256_update(dtls_sha256_ctx*, const uint8_t*, size_t);
+void dtls_sha256_final(uint8_t[DTLS_SHA256_DIGEST_LENGTH], dtls_sha256_ctx*);
+char* dtls_sha256_end(dtls_sha256_ctx*, char[DTLS_SHA256_DIGEST_STRING_LENGTH]);
+char* dtls_sha256_data(const uint8_t*, size_t, char[DTLS_SHA256_DIGEST_STRING_LENGTH]);
 #endif
 
 #ifdef WITH_SHA384
-void DTLS_SHA384_Init(DTLS_SHA384_CTX*);
-void DTLS_SHA384_Update(DTLS_SHA384_CTX*, const uint8_t*, size_t);
-void DTLS_SHA384_Final(uint8_t[DTLS_SHA384_DIGEST_LENGTH], SHA384_CTX*);
-char* DTLS_SHA384_End(DTLS_SHA384_CTX*, char[DTLS_SHA384_DIGEST_STRING_LENGTH]);
-char* DTLS_SHA384_Data(const uint8_t*, size_t, char[DTLS_SHA384_DIGEST_STRING_LENGTH]);
+void dtls_sha384_init(dtls_sha384_ctx*);
+void dtls_sha384_update(dtls_sha384_ctx*, const uint8_t*, size_t);
+void dtls_sha384_final(uint8_t[DTLS_SHA384_DIGEST_LENGTH], SHA384_CTX*);
+char* dtls_sha384_end(dtls_sha384_ctx*, char[DTLS_SHA384_DIGEST_STRING_LENGTH]);
+char* dtls_sha384_data(const uint8_t*, size_t, char[DTLS_SHA384_DIGEST_STRING_LENGTH]);
 #endif
 
 #ifdef WITH_SHA512
-void DTLS_SHA512_Init(DTLS_SHA512_CTX*);
-void DTLS_SHA512_Update(DTLS_SHA512_CTX*, const uint8_t*, size_t);
-void DTLS_SHA512_Final(uint8_t[DTLS_SHA512_DIGEST_LENGTH], DTLS_SHA512_CTX*);
-char* DTLS_SHA512_End(DTLS_SHA512_CTX*, char[DTLS_SHA512_DIGEST_STRING_LENGTH]);
-char* DTLS_SHA512_Data(const uint8_t*, size_t, char[DTLS_SHA512_DIGEST_STRING_LENGTH]);
+void dtls_sha512_init(dtls_sha512_ctx*);
+void dtls_sha512_update(dtls_sha512_ctx*, const uint8_t*, size_t);
+void dtls_sha512_final(uint8_t[DTLS_SHA512_DIGEST_LENGTH], dtls_sha512_ctx*);
+char* dtls_sha512_end(dtls_sha512_ctx*, char[DTLS_SHA512_DIGEST_STRING_LENGTH]);
+char* dtls_sha512_data(const uint8_t*, size_t, char[DTLS_SHA512_DIGEST_STRING_LENGTH]);
 #endif
 
 #else /* SHA2_USE_INTTYPES_H */
 
 #ifdef WITH_SHA256
-void DTLS_SHA256_Init(DTLS_SHA256_CTX *);
-void DTLS_SHA256_Update(DTLS_SHA256_CTX*, const u_int8_t*, size_t);
-void DTLS_SHA256_Final(u_int8_t[DTLS_SHA256_DIGEST_LENGTH], DTLS_SHA256_CTX*);
-char* DTLS_SHA256_End(DTLS_SHA256_CTX*, char[DTLS_SHA256_DIGEST_STRING_LENGTH]);
-char* DTLS_SHA256_Data(const u_int8_t*, size_t, char[DTLS_SHA256_DIGEST_STRING_LENGTH]);
+void dtls_sha256_init(dtls_sha256_ctx *);
+void dtls_sha256_update(dtls_sha256_ctx*, const u_int8_t*, size_t);
+void dtls_sha256_final(u_int8_t[DTLS_SHA256_DIGEST_LENGTH], dtls_sha256_ctx*);
+char* dtls_sha256_end(dtls_sha256_ctx*, char[DTLS_SHA256_DIGEST_STRING_LENGTH]);
+char* dtls_sha256_data(const u_int8_t*, size_t, char[DTLS_SHA256_DIGEST_STRING_LENGTH]);
 #endif
 
 #ifdef WITH_SHA384
-void DTLS_SHA384_Init(DTLS_SHA384_CTX*);
-void DTLS_SHA384_Update(DTLS_SHA384_CTX*, const u_int8_t*, size_t);
-void DTLS_SHA384_Final(u_int8_t[DTLS_SHA384_DIGEST_LENGTH], DTLS_SHA384_CTX*);
-char* DTLS_SHA384_End(DTLS_SHA384_CTX*, char[DTLS_SHA384_DIGEST_STRING_LENGTH]);
-char* DTLS_SHA384_Data(const u_int8_t*, size_t, char[DTLS_SHA384_DIGEST_STRING_LENGTH]);
+void dtls_sha384_init(dtls_sha384_ctx*);
+void dtls_sha384_update(dtls_sha384_ctx*, const u_int8_t*, size_t);
+void dtls_sha384_final(u_int8_t[DTLS_SHA384_DIGEST_LENGTH], dtls_sha384_ctx*);
+char* dtls_sha384_end(dtls_sha384_ctx*, char[DTLS_SHA384_DIGEST_STRING_LENGTH]);
+char* dtls_sha384_data(const u_int8_t*, size_t, char[DTLS_SHA384_DIGEST_STRING_LENGTH]);
 #endif
 
 #ifdef WITH_SHA512
-void DTLS_SHA512_Init(DTLS_SHA512_CTX*);
-void DTLS_SHA512_Update(DTLS_SHA512_CTX*, const u_int8_t*, size_t);
-void DTLS_SHA512_Final(u_int8_t[DTLS_SHA512_DIGEST_LENGTH], DTLS_SHA512_CTX*);
-char* DTLS_SHA512_End(DTLS_SHA512_CTX*, char[DTLS_SHA512_DIGEST_STRING_LENGTH]);
-char* DTLS_SHA512_Data(const u_int8_t*, size_t, char[DTLS_SHA512_DIGEST_STRING_LENGTH]);
+void dtls_sha512_init(dtls_sha512_ctx*);
+void dtls_sha512_update(dtls_sha512_ctx*, const u_int8_t*, size_t);
+void dtls_sha512_final(u_int8_t[DTLS_SHA512_DIGEST_LENGTH], dtls_sha512_ctx*);
+char* dtls_sha512_end(dtls_sha512_ctx*, char[DTLS_SHA512_DIGEST_STRING_LENGTH]);
+char* dtls_sha512_data(const u_int8_t*, size_t, char[DTLS_SHA512_DIGEST_STRING_LENGTH]);
 #endif
 
 #endif /* SHA2_USE_INTTYPES_H */
@@ -182,27 +182,27 @@ char* DTLS_SHA512_Data(const u_int8_t*, size_t, char[DTLS_SHA512_DIGEST_STRING_L
 #else /* NOPROTO */
 
 #ifdef WITH_SHA256
-void DTLS_SHA256_Init();
-void DTLS_SHA256_Update();
-void DTLS_SHA256_Final();
-char* DTLS_SHA256_End();
-char* DTLS_SHA256_Data();
+void dtls_sha256_init();
+void dtls_sha256_update();
+void dtls_sha256_final();
+char* dtls_sha256_end();
+char* dtls_sha256_data();
 #endif
 
 #ifdef WITH_SHA384
-void DTLS_SHA384_Init();
-void DTLS_SHA384_Update();
-void DTLS_SHA384_Final();
-char* DTLS_SHA384_End();
-char* DTLS_SHA384_Data();
+void dtls_sha384_init();
+void dtls_sha384_update();
+void dtls_sha384_final();
+char* dtls_sha384_end();
+char* dtls_sha384_data();
 #endif
 
 #ifdef WITH_SHA512
-void DTLS_SHA512_Init();
-void DTLS_SHA512_Update();
-void DTLS_SHA512_Final();
-char* DTLS_SHA512_End();
-char* DTLS_SHA512_Data();
+void dtls_sha512_init();
+void dtls_sha512_update();
+void dtls_sha512_final();
+char* dtls_sha512_end();
+char* dtls_sha512_data();
 #endif
 
 #endif /* NOPROTO */
index b5c485e..6ac6796 100644 (file)
@@ -52,14 +52,14 @@ int main(int argc, char **argv) {
        int             quiet = 0, hash = 0;
        char            *av, *file = (char*)0;
        FILE            *IN = (FILE*)0;
-       DTLS_SHA256_CTX ctx256;
-       DTLS_SHA384_CTX ctx384;
-       DTLS_SHA512_CTX ctx512;
+       dtls_sha256_ctx ctx256;
+       dtls_sha384_ctx ctx384;
+       dtls_sha512_ctx ctx512;
        unsigned char   buf[BUFLEN];
 
-       DTLS_SHA256_Init(&ctx256);
-       DTLS_SHA384_Init(&ctx384);
-       DTLSSHA512_Init(&ctx512);
+       dtls_sha256_init(&ctx256);
+       dtls_sha384_init(&ctx384);
+       dtls_sha512_init(&ctx512);
 
        /* Read data from STDIN by default */
        fd = fileno(stdin);
@@ -100,28 +100,28 @@ int main(int argc, char **argv) {
        kl = 0;
        while ((l = read(fd,buf,BUFLEN)) > 0) {
                kl += l;
-               DTLS_SHA256_Update(&ctx256, (unsigned char*)buf, l);
-               DTLS_SHA384_Update(&ctx384, (unsigned char*)buf, l);
-               DTLS_SHA512_Update(&ctx512, (unsigned char*)buf, l);
+               dtls_sha256_update(&ctx256, (unsigned char*)buf, l);
+               dtls_sha384_update(&ctx384, (unsigned char*)buf, l);
+               dtls_sha512_update(&ctx512, (unsigned char*)buf, l);
        }
        if (file) {
                fclose(IN);
        }
 
        if (hash & 1) {
-               DTLS_SHA256_End(&ctx256, buf);
+               dtls_sha256_end(&ctx256, buf);
                if (!quiet)
                        printf("SHA-256 (%s) = ", file);
                printf("%s\n", buf);
        }
        if (hash & 2) {
-               DTLS_SHA384_End(&ctx384, buf);
+               dtls_sha384_end(&ctx384, buf);
                if (!quiet)
                        printf("SHA-384 (%s) = ", file);
                printf("%s\n", buf);
        }
        if (hash & 4) {
-               DTLS_SHA512_End(&ctx512, buf);
+               dtls_sha512_end(&ctx512, buf);
                if (!quiet)
                        printf("SHA-512 (%s) = ", file);
                printf("%s\n", buf);
index f012f40..77d17af 100644 (file)
@@ -60,9 +60,9 @@ void printspeed(char *caption, unsigned long bytes, double time) {
 
 
 int main(int argc, char **argv) {
-       DTLS_SHA256_CTX c256;
-       DTLS_SHA384_CTX c384;
-       DTLS_SHA512_CTX c512;
+       dtls_sha256_ctx c256;
+       dtls_sha384_ctx c384;
+       dtls_sha512_ctx c512;
        char            buf[BUFSIZE];
        char            md[DTLS_SHA512_DIGEST_STRING_LENGTH];
        int             bytes, blocks, rep, i, j;
@@ -97,18 +97,18 @@ int main(int argc, char **argv) {
        ave256 = ave384 = ave512 = 0;
        best256 = best384 = best512 = 100000;
        for (i = 0; i < rep; i++) {
-               DTLS_SHA256_Init(&c256);
-               DTLS_SHA384_Init(&c384);
-               DTLS_SHA512_Init(&c512);
+               dtls_sha256_init(&c256);
+               dtls_sha384_init(&c384);
+               dtls_sha512_init(&c512);
        
                gettimeofday(&start, (struct timezone*)0);
                for (j = 0; j < blocks; j++) {
-                       DTLS_SHA256_Update(&c256, (unsigned char*)buf, BUFSIZE);
+                       dtls_sha256_update(&c256, (unsigned char*)buf, BUFSIZE);
                }
                if (bytes % BUFSIZE) {
-                       DTLS_SHA256_Update(&c256, (unsigned char*)buf, bytes % BUFSIZE);
+                       dtls_sha256_update(&c256, (unsigned char*)buf, bytes % BUFSIZE);
                }
-               DTLS_SHA256_End(&c256, md);
+               dtls_sha256_end(&c256, md);
                gettimeofday(&end, (struct timezone*)0);
                t = ((end.tv_sec - start.tv_sec) * 1000000.0 + (end.tv_usec - start.tv_usec)) / 1000000.0;
                ave256 += t;
@@ -119,12 +119,12 @@ int main(int argc, char **argv) {
 
                gettimeofday(&start, (struct timezone*)0);
                for (j = 0; j < blocks; j++) {
-                       DTLS_SHA384_Update(&c384, (unsigned char*)buf, BUFSIZE);
+                       dtls_sha384_update(&c384, (unsigned char*)buf, BUFSIZE);
                }
                if (bytes % BUFSIZE) {
-                       DTLS_SHA384_Update(&c384, (unsigned char*)buf, bytes % BUFSIZE);
+                       dtls_sha384_update(&c384, (unsigned char*)buf, bytes % BUFSIZE);
                }
-               DTLS_SHA384_End(&c384, md);
+               dtls_sha384_end(&c384, md);
                gettimeofday(&end, (struct timezone*)0);
                t = ((end.tv_sec - start.tv_sec) * 1000000.0 + (end.tv_usec - start.tv_usec)) / 1000000.0;
                ave384 += t;
@@ -135,12 +135,12 @@ int main(int argc, char **argv) {
 
                gettimeofday(&start, (struct timezone*)0);
                for (j = 0; j < blocks; j++) {
-                       DTLS_SHA512_Update(&c512, (unsigned char*)buf, BUFSIZE);
+                       dtls_sha512_update(&c512, (unsigned char*)buf, BUFSIZE);
                }
                if (bytes % BUFSIZE) {
-                       DTLS_SHA512_Update(&c512, (unsigned char*)buf, bytes % BUFSIZE);
+                       dtls_sha512_update(&c512, (unsigned char*)buf, bytes % BUFSIZE);
                }
-               DTLS_SHA512_End(&c512, md);
+               dtls_sha512_end(&c512, md);
                gettimeofday(&end, (struct timezone*)0);
                t = ((end.tv_sec - start.tv_sec) * 1000000.0 + (end.tv_usec - start.tv_usec)) / 1000000.0;
                ave512 += t;
index eb72991..1c3fba9 100644 (file)
@@ -92,28 +92,28 @@ struct list {
     (struct_ptr)->LIST_CONCAT(name,_list) = NULL;                      \
   }
 
-static inline void *
+INLINE_API void *
 list_head(list_t list) {
   return *list;
 }
 
-static inline void 
+INLINE_API void 
 list_remove(list_t list, void *item) {
   LL_DELETE(*(struct list **)list, (struct list *)item);
 }
 
-static inline void 
+INLINE_API void 
 list_add(list_t list, void *item) {
   list_remove(list, item);
   LL_APPEND(*(struct list **)list, (struct list *)item);
 }
 
-static inline void 
+INLINE_API void 
 list_push(list_t list, void *item) {
   LL_PREPEND(*(struct list **)list, (struct list *)item);
 }
 
-static inline void *
+INLINE_API void *
 list_pop(list_t list) {
   struct list *l;
   l = *list;
@@ -123,7 +123,7 @@ list_pop(list_t list) {
   return l;
 }
 
-static inline void
+INLINE_API void
 list_insert(list_t list, void *previtem, void *newitem) {
   if(previtem == NULL) {
     list_push(list, newitem);
@@ -133,7 +133,7 @@ list_insert(list_t list, void *previtem, void *newitem) {
   } 
 }
 
-static inline void *
+INLINE_API void *
 list_item_next(void *item)
 {
   return item == NULL? NULL: ((struct list *)item)->next;
index 279d91a..08f1a30 100644 (file)
@@ -6,15 +6,29 @@
 #include <stdio.h>
 #include <string.h>
 #include <errno.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 #include <ctype.h>
+#ifdef HAVE_NETINET_IN_H
 #include <netinet/in.h>
+#endif
 #include <sys/types.h>
+#ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
 #include <arpa/inet.h>
+#endif
+#ifdef HAVE_NETDB_H
 #include <netdb.h>
+#endif
 #include <signal.h>
+#include <getopt.h>
+#include "platform_features.h"
 
 #include "global.h"
 #include "debug.h"
@@ -471,7 +485,11 @@ static void dtls_handle_signal(int sig)
   dtls_free_context(dtls_context);
   dtls_free_context(orig_dtls_context);
   signal(sig, SIG_DFL);
+#ifdef _WIN32
+  exit(sig);
+#else
   kill(getpid(), sig);
+#endif
 }
 
 /* stolen from libcoap: */
@@ -778,7 +796,7 @@ main(int argc, char **argv) {
     return 0;
   }
 
-  if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) ) < 0) {
+  if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on) ) < 0) {
     dtls_alert("setsockopt SO_REUSEADDR: %s\n", strerror(errno));
   }
 #if 0
@@ -790,9 +808,9 @@ main(int argc, char **argv) {
 #endif
   on = 1;
 #ifdef IPV6_RECVPKTINFO
-  if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on) ) < 0) {
+  if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, OPTVAL_T(&on), sizeof(on) ) < 0) {
 #else /* IPV6_RECVPKTINFO */
-  if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, &on, sizeof(on) ) < 0) {
+  if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, OPTVAL_T(&on), sizeof(on) ) < 0) {
 #endif /* IPV6_RECVPKTINFO */
     dtls_alert("setsockopt IPV6_PKTINFO: %s\n", strerror(errno));
   }
index a3ede4d..9a8918a 100644 (file)
@@ -6,13 +6,25 @@
 #include <stdio.h>
 #include <string.h>
 #include <errno.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
 #include <netinet/in.h>
+#endif
 #include <sys/types.h>
+#ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
+#endif
+#ifdef HAVE_NETDB_H
 #include <netdb.h>
+#endif
 #include <signal.h>
+#include <getopt.h>
+#include "platform_features.h"
 
 #include "tinydtls.h"
 #include "dtls.h"
@@ -664,7 +676,7 @@ main(int argc, char **argv) {
     return 0;
   }
 
-  if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) ) < 0) {
+  if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on) ) < 0) {
     dtls_alert("setsockopt SO_REUSEADDR: %s\n", strerror(errno));
   }
 #if 0
@@ -676,9 +688,9 @@ main(int argc, char **argv) {
 #endif
   on = 1;
 #ifdef IPV6_RECVPKTINFO
-  if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on) ) < 0) {
+  if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, OPTVAL_T(&on), sizeof(on) ) < 0) {
 #else /* IPV6_RECVPKTINFO */
-  if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, &on, sizeof(on) ) < 0) {
+  if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, OPTVAL_T(&on), sizeof(on) ) < 0) {
 #endif /* IPV6_RECVPKTINFO */
     dtls_alert("setsockopt IPV6_PKTINFO: %s\n", strerror(errno));
   }
index 8f72f26..b53dc8c 100644 (file)
@@ -44,7 +44,7 @@ finalize_hash(uint8 *buf) {
 #if DTLS_VERSION == 0xfeff
   unsigned char statebuf[sizeof(md5_state_t) + sizeof(SHA_CTX)];
 #elif DTLS_VERSION == 0xfefd
-  unsigned char statebuf[sizeof(DTLS_SHA256_CTX)];
+  unsigned char statebuf[sizeof(dtls_sha256_ctx)];
 #endif
 
   if (!hs_hash[0])
index ac849ef..eca7ff7 100644 (file)
 /** Define to 1 if building with Hardware Abstraction Layer */
 #define DTLS_CRYPTO_HAL 0
 
+#ifndef INLINE_API
+#  if defined(__cplusplus)
+#    define INLINE_API inline
+#  else
+#    ifdef _WIN32
+#      define INLINE_API static __inline
+#    else
+#      define INLINE_API static inline
+#    endif
+#  endif
+#endif
+
 #endif /* _DTLS_TINYDTLS_H_ */
index 9cd4532..dd72b7d 100644 (file)
@@ -338,11 +338,11 @@ do {
     (head)=(head)->next;                                                                       \
   } else {                                                                                     \
     char *_tmp = (char*)(head);                                                                \
-    while (head->next && (head->next != (del))) {                                              \
-      head = head->next;                                                                       \
+    while ((head)->next && ((head)->next != (del))) {                                          \
+      (head) = (head)->next;                                                                   \
     }                                                                                          \
-    if (head->next) {                                                                          \
-      head->next = ((del)->next);                                                              \
+    if ((head)->next) {                                                                        \
+      (head)->next = ((del)->next);                                                            \
     }                                                                                          \
     {                                                                                          \
       char **_head_alias = (char**)&(head);                                                    \
index 9ba4a72..0a3cd39 100755 (executable)
@@ -30,6 +30,7 @@ cp -LR ./extlibs/tinycbor $sourcedir/tmp/extlibs
 rm -rf $sourcedir/tmp/extlibs/tinycbor/tinycbor/.git
 
 cp -R ./extlibs/cjson $sourcedir/tmp/extlibs
+cp -R ./extlibs/gtest $sourcedir/tmp/extlibs
 cp -R ./extlibs/tinydtls $sourcedir/tmp/extlibs
 cp -R ./extlibs/sqlite3 $sourcedir/tmp/extlibs
 cp -R ./extlibs/timer $sourcedir/tmp/extlibs
index 86c1635..8fc70bc 100644 (file)
@@ -29,7 +29,7 @@ target_os = env.get('TARGET_OS')
 build_sample = env.get('BUILD_SAMPLE')
 src_dir = env.get('SRC_DIR')
 
-if target_os not in ['android', 'arduino', 'darwin', 'ios', 'tizen']:
+if target_os not in ['android', 'arduino', 'darwin', 'ios', 'tizen', 'msys_nt', 'windows']:
 
     SConscript(os.path.join('zigbee_wrapper', 'SConscript'))
 
index dc011aa..8caa729 100644 (file)
@@ -139,11 +139,14 @@ OCStackResult SetDeviceInfo()
     static OCDeviceInfo deviceInfo =
         {
             .deviceName = "IoTivity/Zigbee Server Sample",
+            .specVersion = "IoTivity/Zigbee Device Spec Version",
         };
+    char *dmv = OICStrdup("IoTivity/Zigbee Data Model Version");
+    deviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+    deviceInfo.dataModelVersions->value = dmv;
     char *dup = OICStrdup("oic.wk.d");
     deviceInfo.types = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
     deviceInfo.types->value = dup;
-    OICFree(dup);
     return OCSetDeviceInfo(deviceInfo);
 }
 
index 939084d..a586483 100644 (file)
@@ -49,7 +49,7 @@ env.AppendUnique(CPPPATH = [ os.path.join(pi_path, 'include'),
                              os.path.join(pi_path, 'include', 'internal')
                            ])
 
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows']:
        env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
 
 if target_os in ['darwin','ios']:
@@ -81,6 +81,6 @@ if target_os in ['android', 'tizen']:
        calib = env.SharedLibrary('plugin_interface', env.get('PI_SRC'))
 else:
        calib = env.StaticLibrary('plugin_interface', env.get('PI_SRC'))
-env.InstallTarget(calib, 'libplugin_interface')
-env.UserInstallTargetLib(calib, 'libplugin_interface')
+env.InstallTarget(calib, 'plugin_interface')
+env.UserInstallTargetLib(calib, 'plugin_interface')
 
index 947d66d..0c49c79 100644 (file)
@@ -47,7 +47,7 @@ env.AppendUnique(CPPPATH = [ os.path.join(zw_path, 'include'),
                              os.path.join(zw_path, 'zigbee_wrapper', 'include')
                              ])
 
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows']:
        env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
 
 if target_os in ['darwin','ios']:
index ee17a9b..7087fc3 100644 (file)
@@ -427,7 +427,7 @@ void deviceNodeIdChanged(const char * eui, const char * nodeId, PIPlugin_Zigbee*
                                                   nodeId);
     if(result != OC_STACK_OK)
     {
-        OIC_LOG_V(ERROR, TAG, "Failed to update Zigbee Resource NodeId due to result: %s", result);
+        OIC_LOG_V(ERROR, TAG, "Failed to update Zigbee Resource NodeId due to result: %u", result);
     }
 }
 
index be27059..077d21f 100644 (file)
@@ -44,7 +44,7 @@ env.AppendUnique(CPPPATH = [ os.path.join(tw_path, 'include'),
                              os.path.join(tw_path, 'zigbee_wrapper', 'telegesis_wrapper', 'include')
                              ])
 
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows']:
        env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
 
 if target_os in ['darwin','ios']:
index 08728ef..888a1ff 100644 (file)
@@ -420,6 +420,8 @@ OCStackResult TWSetAttribute(char* extendedUniqueId, char* nodeId, char* endpoin
                 SEPARATOR_LENGTH + strlen(attributeType) +
                 SEPARATOR_LENGTH + strlen(newValue) + 1;
 
+    TWEntry* entry = NULL;
+
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
@@ -440,7 +442,6 @@ OCStackResult TWSetAttribute(char* extendedUniqueId, char* nodeId, char* endpoin
     }
     OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
-    TWEntry* entry = NULL;
     twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_WRITEATTR);
     if (twRet != TW_RESULT_OK)
     {
@@ -472,7 +473,10 @@ OCStackResult TWSetAttribute(char* extendedUniqueId, char* nodeId, char* endpoin
     ret = OC_STACK_OK;
 
 exit:
-    TWDeleteEntry(ctx->g_plugin, entry);
+    if (entry != NULL)
+    {
+        TWDeleteEntry(ctx->g_plugin, entry);
+    }
     OICFree(cmdString);
     OIC_LOG_V(INFO, TAG, "Leave TWSetAttribute() with ret=%d", ret);
     return ret;
@@ -504,6 +508,8 @@ OCStackResult TWGetAttribute(char* extendedUniqueId, char* nodeId, char* endpoin
                 SEPARATOR_LENGTH + strlen(clusterId) +
                 SEPARATOR_LENGTH + strlen(attributeId) + 1;
 
+    TWEntry* entry = NULL;
+
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
@@ -532,7 +538,6 @@ OCStackResult TWGetAttribute(char* extendedUniqueId, char* nodeId, char* endpoin
     }
     OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
-    TWEntry* entry = NULL;
     twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_RESPATTR);
     if (twRet != TW_RESULT_OK)
     {
@@ -573,7 +578,10 @@ OCStackResult TWGetAttribute(char* extendedUniqueId, char* nodeId, char* endpoin
     ret = OC_STACK_OK;
 
 exit:
-    TWDeleteEntry(ctx->g_plugin, entry);
+    if (entry != NULL)
+    {
+        TWDeleteEntry(ctx->g_plugin, entry);
+    }
     OICFree(cmdString);
     OIC_LOG_V(INFO, TAG, "Leave TWGetAttribute() with ret=%d", ret);
     return ret;
@@ -614,6 +622,8 @@ OCStackResult TWSwitchOnOff(char* nodeId, char* endpointId, char* newState,
                 SEPARATOR_LENGTH + strlen(newState) + 1;
     }
 
+    TWEntry* entry = NULL;
+
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
@@ -646,7 +656,6 @@ OCStackResult TWSwitchOnOff(char* nodeId, char* endpointId, char* newState,
     }
     OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
-    TWEntry* entry = NULL;
     twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_DFTREP);
     if (twRet != TW_RESULT_OK)
     {
@@ -672,7 +681,10 @@ OCStackResult TWSwitchOnOff(char* nodeId, char* endpointId, char* newState,
     ret = OC_STACK_OK;
 
 exit:
-    TWDeleteEntry(ctx->g_plugin, entry);
+    if (entry != NULL)
+    {
+        TWDeleteEntry(ctx->g_plugin, entry);
+    }
     OICFree(cmdString);
     OIC_LOG_V(INFO, TAG, "Leave TWSwitchOnOff() with ret=%d", ret);
     return ret;
@@ -704,6 +716,8 @@ OCStackResult TWMoveToLevel(char* nodeId, char* endpointId,
             SEPARATOR_LENGTH + strlen(level) +
             SEPARATOR_LENGTH + strlen(transTime) + 1;
 
+    TWEntry* entry = NULL;
+
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
@@ -736,7 +750,6 @@ OCStackResult TWMoveToLevel(char* nodeId, char* endpointId,
 
     OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
-    TWEntry* entry = NULL;
     twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_DFTREP);
     if (twRet != TW_RESULT_OK)
     {
@@ -762,7 +775,10 @@ OCStackResult TWMoveToLevel(char* nodeId, char* endpointId,
     ret = OC_STACK_OK;
 
 exit:
-    TWDeleteEntry(ctx->g_plugin, entry);
+    if (entry != NULL)
+    {
+        TWDeleteEntry(ctx->g_plugin, entry);
+    }
     OICFree(cmdString);
     OIC_LOG_V(INFO, TAG, "Leave TWMoveToLevel() with ret=%d", ret);
     return ret;
@@ -791,6 +807,8 @@ OCStackResult TWSwitchDoorLockState(char* nodeId, char* endpointId, char* newSta
             SEPARATOR_LENGTH + strlen(SENDMODE) +
             SEPARATOR_LENGTH + strlen(newState) + 1;
 
+    TWEntry* entry = NULL;
+
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
@@ -821,7 +839,6 @@ OCStackResult TWSwitchDoorLockState(char* nodeId, char* endpointId, char* newSta
 
     OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
-    TWEntry* entry = NULL;
     twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_DFTREP);
     if (twRet != TW_RESULT_OK)
     {
@@ -848,7 +865,10 @@ OCStackResult TWSwitchDoorLockState(char* nodeId, char* endpointId, char* newSta
     ret = OC_STACK_OK;
 
 exit:
-    TWDeleteEntry(ctx->g_plugin, entry);
+    if (entry != NULL)
+    {
+        TWDeleteEntry(ctx->g_plugin, entry);
+    }
     OICFree(cmdString);
     OIC_LOG_V(INFO, TAG, "Leave TWSwitchDoorLockState() with ret=%d", ret);
     return ret;
@@ -882,6 +902,8 @@ OCStackResult TWColorMoveToColorTemperature(char* nodeId, char* endpointId,
             SEPARATOR_LENGTH + strlen(colorTemperature) +
             SEPARATOR_LENGTH + strlen(transTime) + 1;
 
+    TWEntry* entry = NULL;
+
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
@@ -911,7 +933,6 @@ OCStackResult TWColorMoveToColorTemperature(char* nodeId, char* endpointId,
     }
     OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
-    TWEntry* entry = NULL;
     twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_DFTREP);
     if (twRet != TW_RESULT_OK)
     {
@@ -937,7 +958,10 @@ OCStackResult TWColorMoveToColorTemperature(char* nodeId, char* endpointId,
     ret = OC_STACK_OK;
 
 exit:
-    TWDeleteEntry(ctx->g_plugin, entry);
+    if (entry != NULL)
+    {
+        TWDeleteEntry(ctx->g_plugin, entry);
+    }
     OICFree(cmdString);
     OIC_LOG_V(INFO, TAG, "Leave TWColorMoveToColorTemperature() with ret=%d", ret);
     return ret;
@@ -1710,6 +1734,8 @@ TWResultCode CreatePAN(TWContext* ctx)
 
     OIC_LOG(INFO, TAG, "Enter CreatePAN()");
 
+    TWEntry* entry = NULL;
+    TWEntry* entry2 = NULL;
     TWResultCode twRet1 = TW_RESULT_UNKNOWN;
     TWResultCode twRet2 = TW_RESULT_UNKNOWN;
     TWResultCode ret = TW_RESULT_UNKNOWN;
@@ -1720,8 +1746,6 @@ TWResultCode CreatePAN(TWContext* ctx)
         goto exit;
     }
     OIC_LOG_V(INFO, TAG, "Write %s", AT_CMD_GET_NETWORK_INFO);
-    TWEntry* entry = NULL;
-    TWEntry* entry2 = NULL;
     ret = TWDequeueEntry(ctx->g_plugin, &entry, TW_NETWORK_INFO);
     if (ret != TW_RESULT_OK)
     {
@@ -1782,7 +1806,7 @@ TWResultCode CreatePAN(TWContext* ctx)
     }
 
 exit:
-    if (entry)
+    if (entry != NULL)
     {
         twRet1 = TWDeleteEntry(ctx->g_plugin, entry);
         if(twRet1 != TW_RESULT_OK)
@@ -1950,6 +1974,8 @@ TWResultCode FindClusters(char nodeId[], char endpoint[], TWContext* ctx)
                SEPARATOR_LENGTH + strlen(nodeId) +
                SEPARATOR_LENGTH + strlen(endpoint) + 1;
 
+    TWEntry* entry = NULL;
+
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
@@ -1977,7 +2003,6 @@ TWResultCode FindClusters(char nodeId[], char endpoint[], TWContext* ctx)
     }
     OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
-    TWEntry* entry = NULL;
     ret = TWDequeueEntry(ctx->g_plugin, &entry, TW_SIMPLEDESC);
     if (ret != TW_RESULT_OK)
     {
@@ -2002,7 +2027,10 @@ TWResultCode FindClusters(char nodeId[], char endpoint[], TWContext* ctx)
     }
 
 exit:
-    TWDeleteEntry(ctx->g_plugin, entry);
+    if (entry != NULL)
+    {
+        TWDeleteEntry(ctx->g_plugin, entry);
+    }
     OICFree(cmdString);
     OIC_LOG_V(INFO, TAG, "Leave FindClusters() with ret=%d", ret);
     return ret;
@@ -2019,6 +2047,8 @@ TWResultCode GetRemoteEUI(char *nodeId, char* outRemoteEUI, TWContext* ctx)
 
     int size = strlen(AT_CMD_REMOTE_EUI_REQUEST) + strlen(nodeId) +
                SEPARATOR_LENGTH + strlen(nodeId) + 1;
+    TWEntry* entry = NULL;
+
     char* cmdString = (char*)OICMalloc(size * sizeof(char));
     if (cmdString == NULL)
     {
@@ -2045,7 +2075,6 @@ TWResultCode GetRemoteEUI(char *nodeId, char* outRemoteEUI, TWContext* ctx)
     }
     OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
 
-    TWEntry* entry = NULL;
     ret = TWDequeueEntry(ctx->g_plugin, &entry, TW_ADDRESS_RESPONSE);
     if (ret != TW_RESULT_OK)
     {
@@ -2085,7 +2114,10 @@ TWResultCode GetRemoteEUI(char *nodeId, char* outRemoteEUI, TWContext* ctx)
 exit:
     memset(ctx->g_WIPRemoteEUI, '\0', sizeof(ctx->g_WIPRemoteEUI));
     memset(ctx->g_WIPRemoteNodeId, '\0', sizeof(ctx->g_WIPRemoteNodeId));
-    TWDeleteEntry(ctx->g_plugin, entry);
+    if (entry != NULL)
+    {
+        TWDeleteEntry(ctx->g_plugin, entry);
+    }
     OICFree(cmdString);
     OIC_LOG_V(INFO, TAG, "Leave GetRemoteEUI() with ret=%d", ret);
     return ret;
@@ -2537,7 +2569,7 @@ TWResultCode TelSimpleDescInClusterHandler(int count, char* tokens[], TWContext*
     {
         OIC_LOG(ERROR, TAG, "Invalid Params");
         ret = TW_RESULT_ERROR_INVALID_PARAMS;
-               goto exit;
+        goto exit;
     }
 
     if (ctx->g_WIPDevice == NULL)
index b07bc95..554bb9d 100644 (file)
@@ -23,8 +23,6 @@
 #
 ##
 
-import os
-
 Import('env')
 
 target_os = env.get('TARGET_OS')
@@ -33,7 +31,7 @@ src_dir = env.get('SRC_DIR')
 # Build liblogger
 SConscript('csdk/logger/SConscript')
 
-if target_os not in ['arduino', 'darwin', 'ios', 'android']:
+if target_os not in ['arduino', 'darwin', 'ios', 'android', 'msys_nt', 'windows']:
        env.AppendUnique(LIBS=['rt'])
 
 # Build libcoap
@@ -66,7 +64,7 @@ if target_os not in ['arduino','darwin','ios','android']:
        # Build examples
        SConscript('examples/SConscript')
 
-if target_os == 'linux':
+if target_os in ['linux', 'windows']:
        # Build C Samples
        SConscript('csdk/stack/samples/linux/SimpleClientServer/SConscript')
 
@@ -86,3 +84,10 @@ elif target_os == 'darwin':
 
 elif target_os == 'arduino':
        SConscript('csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript')
+
+elif target_os == 'msys_nt':
+       # Build secure samples. Using linux samples for now.
+       SConscript('csdk/stack/samples/linux/secure/SConscript')
+
+       # Build C/C++ unit tests
+       SConscript('unit_tests.scons')
index a9285ae..2b46f5c 100644 (file)
@@ -24,18 +24,22 @@ import os
 
 target_os = env.get('TARGET_OS')
 
+# 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, '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')
         ])
 
 if target_os == 'tizen':
        env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 else:
-       env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/c_common')])
+       env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'c_common')])
 
 if target_os in ['tizen', 'linux']:
        env.ParseConfig("pkg-config --cflags --libs uuid")
@@ -43,6 +47,7 @@ if target_os in ['tizen', 'linux']:
 env.PrependUnique(LIBS = ['c_common'])
 
 common_env = env.Clone()
+common_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource')])
 
 ######################################################################
 # Build flags
index e096fc5..7a91dea 100644 (file)
@@ -29,9 +29,9 @@
 extern "C" {
 #endif
 
-#if defined(__ANDROID__) || defined(__linux__)
+#ifndef ARDUINO
 #include <time.h>
-#elif defined ARDUINO
+#else
 // MEGA has 16 input pins whereas Due has only 12 input pins
 #define ANALOG_IN (10)
 #endif
index 95472b6..118aeee 100644 (file)
 #define _POSIX_C_SOURCE 200809L
 #endif
 
-#if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__)
-#include "fcntl.h"
-#include "unistd.h"
+#include "platform_features.h"
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_STDLIB_H
 #include <stdlib.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
+#endif
+#ifdef HAVE_TIME_H
 #include <time.h>
+#endif
 #if defined(__ANDROID__)
 #include <ctype.h>
 #include <linux/time.h>
 #endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
 #endif
 #include "ocrandom.h"
 #include <stdio.h>
 
-#if !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
+#ifdef HAVE_UUID_UUID_H
 #include <uuid/uuid.h>
 #endif
 
-#if !defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__) || defined(__TIZEN__)
 #define NANO_SEC 1000000000
-#endif
 
 #ifdef ARDUINO
 #include "Arduino.h"
@@ -104,13 +114,18 @@ uint8_t GetRandomBit()
 
 int8_t OCSeedRandom()
 {
-#if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__) || defined(__TIZEN__)
+#ifndef ARDUINO
     // Get current time to Seed.
     uint64_t currentTime = 0;
 #ifdef __ANDROID__
     struct timespec getTs;
     clock_gettime(CLOCK_MONOTONIC, &getTs);
     currentTime = (getTs.tv_sec * (uint64_t)NANO_SEC + getTs.tv_nsec)/1000;
+#elif _WIN32
+    LARGE_INTEGER count;
+    if (QueryPerformanceCounter(&count)) {
+        currentTime = count.QuadPart;
+    }
 #elif  _POSIX_TIMERS > 0
     struct timespec ts;
     clock_gettime(CLOCK_MONOTONIC, &ts);
@@ -120,7 +135,7 @@ int8_t OCSeedRandom()
     gettimeofday(&tv, NULL);
     currentTime = tv.tv_sec * (uint64_t)1000000 + tv.tv_usec;
 #endif
-
+#if defined(__unix__) || defined(__APPLE__)
     int32_t fd = open("/dev/urandom", O_RDONLY);
     if (fd >= 0)
     {
@@ -140,6 +155,7 @@ int8_t OCSeedRandom()
         srand(randomSeed | currentTime);
     }
     else
+#endif
     {
         // Do time based seed when problem in accessing "/dev/urandom"
         srand(currentTime);
@@ -184,15 +200,11 @@ uint32_t OCGetRandom()
 
 uint8_t OCGetRandomByte(void)
 {
-#if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__)
-    return rand() & 0x00FF;
-#elif defined ARDUINO
 #ifdef HAVE_SRANDOM
     return random() & 0x00FF;
 #else
     return rand() & 0x00FF;
 #endif
-#endif
 }
 
 uint32_t OCGetRandomRange(uint32_t firstBound, uint32_t secondBound)
@@ -273,7 +285,7 @@ OCRandomUuidResult OCGenerateUuid(uint8_t uuid[UUID_SIZE])
     uuid[15] = parseUuidPart(&uuidString[34]);
 
     return RAND_UUID_OK;
-#elif !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
+#elif defined(HAVE_UUID_UUID_H)
     // note: uuid_t is typedefed as unsigned char[16] on linux/apple
     uuid_generate(uuid);
     return RAND_UUID_OK;
@@ -318,7 +330,7 @@ OCRandomUuidResult OCGenerateUuidString(char uuidString[UUID_STRING_SIZE])
         close(fd);
         return RAND_UUID_READ_ERROR;
     }
-#elif !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
+#elif defined(HAVE_UUID_UUID_H)
     uint8_t uuid[UUID_SIZE];
     int8_t ret = OCGenerateUuid(uuid);
 
index 3ecdd8a..0deba60 100644 (file)
@@ -28,6 +28,7 @@
 #define US_PER_MS   (1000)
 #define NS_PER_US   (1000)
 #define NS_PER_MS   (1000000)
+#define HNS_PER_US  (10)
 
 
 #ifdef __cplusplus
index 2415d42..0cf2388 100644 (file)
@@ -34,7 +34,9 @@
 
 #include <stddef.h>        // For NULL
 
-#ifndef WITH_ARDUINO
+#if defined(_WIN32)
+# include <windows.h>
+#elif !defined(WITH_ARDUINO)
 # if _POSIX_TIMERS > 0
 #  include <time.h>        // For clock_gettime()
 # else
@@ -50,6 +52,21 @@ uint64_t OICGetCurrentTime(OICTimePrecision precision)
 
 #ifdef WITH_ARDUINO
     currentTime = (TIME_IN_MS == precision) ? millis() : micros();
+#elif defined(_WIN32)
+    FILETIME fileTime;
+
+    GetSystemTimePreciseAsFileTime(&fileTime);
+
+    // fileTime should now be a QWORD hundred-nanoseconds time since 1601
+
+    // MSDN recommends using ULARGE_INTEGER as an intermediate representation for math.
+    ULARGE_INTEGER time = { .LowPart  = fileTime.dwLowDateTime,
+                            .HighPart = fileTime.dwHighDateTime };
+
+    currentTime =
+    (TIME_IN_MS == precision)
+        ? time.QuadPart / (HNS_PER_US * US_PER_MS)
+        : time.QuadPart / (HNS_PER_US);
 #else
 # if _POSIX_TIMERS > 0
 #   if defined(CLOCK_MONOTONIC_COARSE)
index 3f712a3..4335e49 100644 (file)
 
 
 #if (__cplusplus >=201103L) || defined(__GXX_EXPERIMENTAL_CXX0X__)
-    #define SUPPORTS_DEFAULT_CTOR
+#  define SUPPORTS_DEFAULT_CTOR
 #endif
 
 #if (__STDC_VERSION__ >= 201112L)
-    #include <assert.h>
-    #define OC_STATIC_ASSERT(condition, msg) static_assert(condition, msg)
+#  include <assert.h>
+#  define OC_STATIC_ASSERT(condition, msg) static_assert(condition, msg)
+#elif defined(_WIN32)
+#  if defined(__msys_nt__) && !defined(__cplusplus)
+#    define static_assert _Static_assert
+#  endif
+#  define OC_STATIC_ASSERT(condition, msg) static_assert(condition, msg)
 #else
-    #define OC_STATIC_ASSERT(condition, msg) ((void)sizeof(char[2*!!(condition) - 1]))
+#  define OC_STATIC_ASSERT(condition, msg) ((void)sizeof(char[2*!!(condition) - 1]))
+#endif
+
+#ifndef INLINE_API
+#  if defined(__cplusplus)
+#    define INLINE_API inline
+#  else
+#    ifdef _MSC_VER
+#      define INLINE_API static __inline
+#    else
+#      define INLINE_API static inline
+#    endif
+#  endif
+#endif
+
+#ifdef _MSC_VER
+#  ifdef OC_EXPORT_DLL
+#    define OC_EXPORT __declspec(dllexport)
+#  else
+#    define OC_EXPORT __declspec(dllimport)
+#  endif
+#  ifdef ENABLE_TEST_EXPORTS
+#    define OC_EXPORT_TEST OC_EXPORT
+#  else
+#    define OC_EXPORT_TEST
+#  endif
+#  define OC_ANNOTATE_UNUSED
+#else
+#  define OC_ANNOTATE_UNUSED  __attribute__((unused))
+#  define OC_EXPORT
+#  define OC_EXPORT_TEST
+#endif
+
+#ifdef _WIN32
+#  define __func__ __FUNCTION__
+#  define strncasecmp _strnicmp
+#  define strtok_r strtok_s
+#  if _MSC_VER && (_MSC_VER < 1900)
+#    include "windows/include/vs12_snprintf.h"
+#  endif
+#  define ssize_t SSIZE_T
+#  define F_OK                0
+#  define sleep(SECS)         Sleep(1000*(SECS))
+#  ifdef __cplusplus
+#    define SUPPORTS_DEFAULT_CTOR
+#  endif
+#  include "windows/include/win_sleep.h"
+#  include "windows/include/pthread_create.h"
+#endif
+
+#ifdef HAVE_WINSOCK2_H
+#  define OPTVAL_T(t)    (const char*)(t)
+#else
+#  define OPTVAL_T(t)    (t)
 #endif
 
 #endif
diff --git a/resource/c_common/windows/SConscript b/resource/c_common/windows/SConscript
new file mode 100644 (file)
index 0000000..85c4bf3
--- /dev/null
@@ -0,0 +1,26 @@
+##
+# Builds Windows-specific helper library
+##
+Import('env')
+import os.path
+
+# Include any headers that might be missing on Windows
+env.AppendUnique(CPPPATH = [os.path.abspath('./include')])
+
+######################################################################
+# Source files and Targets
+######################################################################
+src_dir = os.path.abspath('./src')
+helper_src = [
+       os.path.join(src_dir, 'getopt.c'),
+       os.path.join(src_dir, 'win_sleep.c'),
+       os.path.join(src_dir, 'snprintf.c'),
+       os.path.join(src_dir, 'pthread_create.c')
+       ]
+
+static_libwinhelper = env.StaticLibrary('win_helper', helper_src)
+env.InstallTarget(static_libwinhelper, 'win_helper')
+env.UserInstallTargetLib(static_libwinhelper, 'win_helper')
+
+env.AppendUnique(LIBS = ['win_helper'])
+
diff --git a/resource/c_common/windows/include/getopt.h b/resource/c_common/windows/include/getopt.h
new file mode 100644 (file)
index 0000000..afa578e
--- /dev/null
@@ -0,0 +1,20 @@
+/** @todo: Add Microsoft license information */
+
+#ifndef GETOPT_H__
+#define GETOPT_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern char *optarg;
+extern int optind;
+
+int getopt(int argc, char *const argv[], const char *optstring);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/resource/c_common/windows/include/pthread_create.h b/resource/c_common/windows/include/pthread_create.h
new file mode 100644 (file)
index 0000000..de8cf46
--- /dev/null
@@ -0,0 +1,26 @@
+/** @todo: Add Microsoft license information */
+
+#ifndef PTHREAD_CREATE_H__
+#define PTHREAD_CREATE_H__
+#ifndef WIN_PTHREADS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void* pthread_t;
+typedef void pthread_attr_t;
+
+int pthread_create(
+   pthread_t *thread,
+   const pthread_attr_t *attr,
+   void *(*start_routine)(void *),
+   void *arg);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //WIN_PTHREADS_H
+#endif //__PTHREAD_CREATE_H__
+
diff --git a/resource/c_common/windows/include/vs12_snprintf.h b/resource/c_common/windows/include/vs12_snprintf.h
new file mode 100644 (file)
index 0000000..6416332
--- /dev/null
@@ -0,0 +1,40 @@
+/* *****************************************************************
+*
+* 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.
+*
+******************************************************************/
+
+#ifndef VS12_SNPRINTF_H__
+#define VS12_SNPRINTF_H__
+
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int vs12_snprintf(char *buffer, size_t count, const char *format, ...);
+
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+# define snprintf vs12_snprintf
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/resource/c_common/windows/include/win_sleep.h b/resource/c_common/windows/include/win_sleep.h
new file mode 100644 (file)
index 0000000..e03eaa5
--- /dev/null
@@ -0,0 +1,45 @@
+/* *****************************************************************
+*
+* 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.
+*
+******************************************************************/
+
+#ifndef WIN_SLEEP_H__
+#define WIN_SLEEP_H__
+
+#include <time.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+struct timespec
+{
+    time_t tv_sec;  // Seconds - >= 0
+    long   tv_nsec; // Nanoseconds - [0, 999999999]
+};
+#endif
+
+int nanosleep(const struct timespec *req, struct timespec *rem);
+int usleep(unsigned int usec);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/resource/c_common/windows/src/getopt.c b/resource/c_common/windows/src/getopt.c
new file mode 100644 (file)
index 0000000..abc4184
--- /dev/null
@@ -0,0 +1,35 @@
+/** @todo: Add Microsoft license information */
+
+#include "getopt.h"
+#include <windows.h>
+
+char* optarg = NULL;
+int optind = 1;
+
+int getopt(int argc, char *const argv[], const char *optstring)
+{
+    if ((optind >= argc) || (argv[optind][0] != '-') || (argv[optind][0] == 0))
+    {
+        return -1;
+    }
+
+    int opt = argv[optind][1];
+    const char *p = strchr(optstring, opt);
+
+    if (p == NULL)
+    {
+        return '?';
+    }
+    if (p[1] == ':')
+    {
+        optind++;
+        if (optind >= argc)
+        {
+            return '?';
+        }
+        optarg = argv[optind];
+        optind++;
+    }
+    return opt;
+}
+
diff --git a/resource/c_common/windows/src/pthread_create.c b/resource/c_common/windows/src/pthread_create.c
new file mode 100644 (file)
index 0000000..c7a592d
--- /dev/null
@@ -0,0 +1,23 @@
+/** @todo: Add Microsoft license information */
+
+#include "pthread_create.h"
+#include <windows.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int pthread_create(
+    pthread_t *thread,
+    const pthread_attr_t *attr,
+    void *(*start_routine)(void *),
+    void *arg)
+{
+    *thread = CreateThread(NULL, 0, (PTHREAD_START_ROUTINE)start_routine, arg, 0, NULL);
+    return (*thread == NULL) ? GetLastError() : 0;
+}
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/resource/c_common/windows/src/snprintf.c b/resource/c_common/windows/src/snprintf.c
new file mode 100644 (file)
index 0000000..c9c7de5
--- /dev/null
@@ -0,0 +1,41 @@
+/* *****************************************************************
+*
+* 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.
+*
+******************************************************************/
+
+#include "vs12_snprintf.h"
+#include <stdio.h>
+#include <stdarg.h>
+
+int vs12_snprintf(char *buffer, size_t count, const char *format, ...)
+{
+    va_list args;
+
+    va_start(args, format);
+
+    int length = _vsnprintf(buffer, count, format, args);
+
+    va_end(args);
+
+    if (length > count)
+    {
+        buffer[count - 1] = '\0';
+    }
+
+    return length;
+}
+
diff --git a/resource/c_common/windows/src/win_sleep.c b/resource/c_common/windows/src/win_sleep.c
new file mode 100644 (file)
index 0000000..43d7194
--- /dev/null
@@ -0,0 +1,62 @@
+/* *****************************************************************
+*
+* 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.
+*
+******************************************************************/
+
+#include <assert.h>
+#include <windows.h>
+#include <errno.h>
+#include "win_sleep.h"
+
+#include "logger.h"
+#define TAG  "WIN_SLEEP"
+
+#define NS_PER_MS  (1000000)
+#define US_PER_MS  (1000)
+
+#define ASSERT_AND_FAIL(EXPRESSION) {    \
+    assert((EXPRESSION));                \
+    if (!(EXPRESSION))                   \
+    {                                    \
+        errno = EINVAL;                  \
+        return -1;                       \
+    }                                    \
+}
+
+int usleep(unsigned int usec)
+{
+    assert((usec % US_PER_MS) == 0); // granularity check
+    Sleep((usec + US_PER_MS - 1) / US_PER_MS);
+    return 0;
+}
+
+int nanosleep(const struct timespec *req, struct timespec *rem)
+{
+    if (req == NULL)
+    {
+        OIC_LOG(DEBUG, TAG, "nanosleep: req param should not be null");
+    }
+    ASSERT_AND_FAIL(req != NULL);
+    ASSERT_AND_FAIL(rem == NULL);
+    ASSERT_AND_FAIL(req->tv_sec == 0);
+    assert((req->tv_nsec % NS_PER_MS) == 0); // granularity check
+
+    Sleep((req->tv_nsec + NS_PER_MS - 1) / NS_PER_MS);
+
+    return 0;
+}
+
index a9ea0f9..c791e3f 100644 (file)
@@ -58,7 +58,7 @@ liboctbstack_env.PrependUnique(CPPPATH = [
                'security/provisioning/include',
                ])
 
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows']:
        liboctbstack_env.AppendUnique(CPPDEFINES  = ['WITH_POSIX'])
        liboctbstack_env.AppendUnique(CFLAGS = ['-std=c99'])
 
@@ -67,12 +67,13 @@ if liboctbstack_env.get('ROUTING') == 'GW':
 elif liboctbstack_env.get('ROUTING') == 'EP':
        liboctbstack_env.AppendUnique(CPPDEFINES = ['ROUTING_EP'])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
        liboctbstack_env.AppendUnique(CFLAGS = ['-Wall'])
 
 liboctbstack_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 
-if target_os in ['android', 'linux', 'tizen']:
+liboctbstack_env.PrependUnique(LIBS = ['ocsrm', 'coap'])
+if target_os in ['android', 'linux', 'tizen', 'msys_nt', 'windows']:
        liboctbstack_env.PrependUnique(LIBS = ['connectivity_abstraction'])
 
        if with_ra_ibb:
@@ -81,24 +82,27 @@ if target_os in ['android', 'linux', 'tizen']:
                if with_ra:
                        liboctbstack_env.AppendUnique(LIBS = ['ra_xmpp'])
 
-liboctbstack_env.AppendUnique(LIBS = ['coap', 'm'])
-liboctbstack_env.PrependUnique(LIBS = ['ocsrm'])
+if target_os in ['windows', 'msys_nt']:
+       liboctbstack_env.AppendUnique(CPPDEFINES  = ['OC_EXPORT_DLL'])
+       liboctbstack_env.AppendUnique(LIBS = ['ws2_32', 'advapi32', 'iphlpapi'])
+else:
+       liboctbstack_env.AppendUnique(LIBS = ['m'])
 
 if target_os in ['tizen', 'linux']:
        liboctbstack_env.ParseConfig("pkg-config --cflags --libs uuid")
 
-if target_os not in ['android', 'arduino', 'windows', 'winrt']:
+if target_os not in ['android', 'arduino', 'windows', 'msys_nt']:
        liboctbstack_env.AppendUnique(LIBS = ['pthread'])
 
 if target_os == 'arduino':
        liboctbstack_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO'])
-elif target_os not in ['darwin','ios']:
+elif target_os not in ['darwin','ios', 'msys_nt', 'windows']:
        liboctbstack_env.AppendUnique(CFLAGS = ['-fPIC'])
 if target_os in ['darwin', 'ios']:
        env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
        liboctbstack_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
        liboctbstack_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-if target_os not in ['arduino']:
+if target_os not in ['arduino', 'windows']:
        liboctbstack_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
 if target_os == 'android':
     liboctbstack_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,liboctbstack.so'])
@@ -114,6 +118,7 @@ if env.get('DTLS_WITH_X509') == '1':
 
 if env.get('WITH_RD') == '1':
        liboctbstack_env.PrependUnique(CPPPATH = ['../../service/resource-directory/include'])
+       liboctbstack_env.PrependUnique(LIBPATH = [env.get('BUILD_DIR') + 'service/resource-directory/include'])
        liboctbstack_env.AppendUnique(CPPDEFINES = ['-DWITH_RD'])
        liboctbstack_env.AppendUnique(LIBS = ['resource_directory'])
 
@@ -147,18 +152,22 @@ if with_tcp == True:
 
 liboctbstack_src.extend(env['cbor_files'])
 
-if target_os in ['arduino','darwin','ios'] :
-       static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src)
-       liboctbstack_env.InstallTarget(static_liboctbstack, 'liboctbstack')
-       liboctbstack_env.UserInstallTargetLib(static_liboctbstack, 'liboctbstack')
-       liboctbstack_env.UserInstallTargetHeader('stack/include/ocstackconfig.h', 'resource', 'ocstackconfig.h')
-       liboctbstack_env.UserInstallTargetHeader('stack/include/octypes.h', 'resource', 'octypes.h')
-else:
-       static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src)
+if target_os == 'windows':
+       liboctbstack_env.AppendUnique(CPPDEFINES = ['CBOR_API=__declspec(dllexport)',
+                                                   'CBOR_PRIVATE_API=__declspec(dllexport)'
+    ])
+
+static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src)
+octbstack_libs = Flatten(static_liboctbstack)
+
+if target_os not in ['arduino','darwin','ios'] :
        shared_liboctbstack = liboctbstack_env.SharedLibrary('octbstack', liboctbstack_src)
-       liboctbstack_env.InstallTarget([static_liboctbstack, shared_liboctbstack], 'liboctbstack')
-       liboctbstack_env.UserInstallTargetLib([static_liboctbstack, shared_liboctbstack], 'liboctbstack')
-       liboctbstack_env.UserInstallTargetHeader('stack/include/ocstackconfig.h', 'resource', 'ocstackconfig.h')
-       liboctbstack_env.UserInstallTargetHeader('stack/include/octypes.h', 'resource', 'octypes.h')
+       octbstack_libs += Flatten(shared_liboctbstack)
        liboctbstack_env.UserInstallTargetHeader('stack/include/ocstack.h', 'resource', 'ocstack.h')
        liboctbstack_env.UserInstallTargetHeader('stack/include/ocpresence.h', 'resource', 'ocpresence.h')
+
+liboctbstack_env.InstallTarget(octbstack_libs, 'octbstack')
+liboctbstack_env.UserInstallTargetLib(octbstack_libs, 'octbstack')
+
+liboctbstack_env.UserInstallTargetHeader('stack/include/ocstackconfig.h', 'resource', 'ocstackconfig.h')
+liboctbstack_env.UserInstallTargetHeader('stack/include/octypes.h', 'resource', 'octypes.h')
index d533f71..e4aa2eb 100644 (file)
@@ -35,6 +35,8 @@ if 'ALL' in transport:
                env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER', 'NFC_ADAPTER'])
        elif target_os in['darwin','ios']:
                env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','NO_EDR_ADAPTER','NO_LE_ADAPTER'])
+       elif target_os in ['msys_nt', 'windows']:
+               env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','NO_EDR_ADAPTER','NO_LE_ADAPTER'])
        else:
                env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER'])
        print "CA Transport is ALL"
index 19e1520..130c3da 100644 (file)
 #include <sys/poll.h>
 #endif
 
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#include <mswsock.h>
+#endif
+
 #ifdef __cplusplus
 extern "C"
 {
@@ -128,13 +133,34 @@ typedef char *CAURI_t;
  */
 typedef char *CAToken_t;
 
-// The following flags are the same as the equivalent OIC values in
-// octypes.h, allowing direct copying with slight fixup.
-// The CA layer should used the OC types when build allows that.
+/*
+ * Socket types and error definitions
+ */
+#ifdef HAVE_WINSOCK2_H
+# define OC_SOCKET_ERROR      SOCKET_ERROR
+# define OC_INVALID_SOCKET    INVALID_SOCKET
+typedef HANDLE CASocketFd_t;
+#else // HAVE_WINSOCK2_H
+# define OC_SOCKET_ERROR      (-1)
+# define OC_INVALID_SOCKET    (-1)
+typedef int    CASocketFd_t;
+#endif
+
+/*
+ * The following flags are the same as the equivalent OIC values in
+ * octypes.h, allowing direct copying with slight fixup.
+ * The CA layer should used the OC types when build allows that.
+ */
 #ifdef RA_ADAPTER
 #define MAX_ADDR_STR_SIZE_CA (256)
 #else
-#define MAX_ADDR_STR_SIZE_CA (40)
+/*
+ * Max Address could be "coap+tcp://[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:yyy.yyy.yyy.yyy]:xxxxx"
+ * Which is 64, +1 for null terminator => 65
+ * OCDevAddr (defined in OCTypes.h) must be the same
+ * as CAEndpoint_t (defined here)
+ */
+#define MAX_ADDR_STR_SIZE_CA (65)
 #endif
 
 typedef enum
@@ -250,7 +276,7 @@ typedef struct
     CATransportFlags_t      flags;      // transport modifiers
     uint16_t                port;       // for IP
     char                    addr[MAX_ADDR_STR_SIZE_CA]; // address for all
-    uint32_t                interface;  // usually zero for default interface
+    uint32_t                ifindex;    // usually zero for default interface
 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
     char                    routeData[MAX_ADDR_STR_SIZE_CA]; /**< GatewayId:ClientId of
                                                                     destination. **/
@@ -440,8 +466,8 @@ typedef struct
  */
 typedef struct
 {
-    int fd;        /**< socket fd */
-    uint16_t port; /**< socket port */
+    CASocketFd_t fd;    /**< socket fd */
+    uint16_t port;      /**< socket port */
 } CASocket_t;
 
 #define HISTORYSIZE (4)
@@ -468,6 +494,28 @@ typedef struct
     int32_t ifIndex; /**< network interface index */
 } CAIfItem_t;
 
+/**
+ * Hold the port number assigned from application.
+ * It will be used when creating a socket.
+ */
+typedef struct
+{
+    struct udpports
+    {
+        uint16_t u6;    /**< unicast IPv6 socket port */
+        uint16_t u6s;   /**< unicast IPv6 socket secure port */
+        uint16_t u4;    /**< unicast IPv4 socket port */
+        uint16_t u4s;   /**< unicast IPv4 socket secure port */
+    } udp;
+#ifdef TCP_ADAPTER
+    struct tcpports
+    {
+        uint16_t u4;    /**< unicast IPv4 socket port */
+        uint16_t u6;    /**< unicast IPv6 socket port */
+    } tcp;
+#endif
+} CAPorts_t;
+
 typedef struct
 {
     CATransportFlags_t clientFlags; /**< flag for client */
@@ -475,26 +523,35 @@ typedef struct
     bool client; /**< client mode */
     bool server; /**< server mode */
 
+    CAPorts_t ports;
+
     struct sockets
     {
-        void *threadpool;   /**< threadpool between Initialize and Start */
-        CASocket_t u6;      /**< unicast   IPv6 */
-        CASocket_t u6s;     /**< unicast   IPv6 secure */
-        CASocket_t u4;      /**< unicast   IPv4 */
-        CASocket_t u4s;     /**< unicast   IPv4 secure */
-        CASocket_t m6;      /**< multicast IPv6 */
-        CASocket_t m6s;     /**< multicast IPv6 secure */
-        CASocket_t m4;      /**< multicast IPv4 */
-        CASocket_t m4s;     /**< multicast IPv4 secure */
-        int netlinkFd;      /**< netlink */
-        int shutdownFds[2]; /**< shutdown pipe */
-        int selectTimeout;  /**< in seconds */
-        int maxfd;          /**< highest fd (for select) */
-        bool started;       /**< the IP adapter has started */
-        bool terminate;     /**< the IP adapter needs to stop */
-        bool ipv6enabled;   /**< IPv6 enabled by OCInit flags */
-        bool ipv4enabled;   /**< IPv4 enabled by OCInit flags */
-        bool dualstack;     /**< IPv6 and IPv4 enabled */
+        void *threadpool;           /**< threadpool between Initialize and Start */
+        CASocket_t u6;              /**< unicast   IPv6 */
+        CASocket_t u6s;             /**< unicast   IPv6 secure */
+        CASocket_t u4;              /**< unicast   IPv4 */
+        CASocket_t u4s;             /**< unicast   IPv4 secure */
+        CASocket_t m6;              /**< multicast IPv6 */
+        CASocket_t m6s;             /**< multicast IPv6 secure */
+        CASocket_t m4;              /**< multicast IPv4 */
+        CASocket_t m4s;             /**< multicast IPv4 secure */
+        CASocketFd_t netlinkFd;     /**< netlink */
+#if defined(_WIN32)
+        WSAEVENT shutdownEvent;     /**< Event used to signal threads to stop */
+#else
+        int shutdownFds[2];         /**< fds used to signal threads to stop */
+#endif
+        int selectTimeout;          /**< in seconds */
+        int maxfd;                  /**< highest fd (for select) */
+        bool started;               /**< the IP adapter has started */
+        bool terminate;             /**< the IP adapter needs to stop */
+        bool ipv6enabled;           /**< IPv6 enabled by OCInit flags */
+        bool ipv4enabled;           /**< IPv4 enabled by OCInit flags */
+        bool dualstack;             /**< IPv6 and IPv4 enabled */
+#if defined (_WIN32)
+        LPFN_WSARECVMSG wsaRecvMsg; /**< Win32 function pointer to WSARecvMsg() */
+#endif
 
         struct networkmonitors
         {
index 3d12870..cab30a7 100644 (file)
@@ -121,7 +121,7 @@ typedef int (*CAGetDTLSX509CredentialsHandler)(CADtlsX509Creds_t *credInfo);
  *                                  credInfo which is then freed by CA
  * @return  NONE
  */
-typedef void (*CAGetDTLSCrlHandler)(ByteArray crlInfo);
+typedef void (*CAGetDTLSCrlHandler)(ByteArray* crlInfo);
 
 /**
  * @brief   Register callback to get DTLS Cert credentials.
index cdd377b..93f927f 100644 (file)
@@ -70,6 +70,26 @@ CAResult_t CASetAutoConnectionDeviceInfo(const char* address);
  */
 CAResult_t CAUnsetAutoConnectionDeviceInfo(const char* address);
 
+/**
+ * Set the port number to assign .
+ * @param[in]   adapter     Transport adapter information.
+ * @param[in]   flag        Transport flag information.
+ * @param[in]   port        The port number to use.
+ *
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED.
+ */
+CAResult_t CASetPortNumberToAssign(CATransportAdapter_t adapter,
+                                   CATransportFlags_t flag, uint16_t port);
+
+/**
+ * Get the assigned port number currently.
+ * @param[in]   adapter     Transport adapter information.
+ * @param[in]   flag        Transport flag information.
+ *
+ * @return  assigned port number information.
+ */
+uint16_t CAGetAssignedPortNumber(CATransportAdapter_t adapter, CATransportFlags_t flag);
+
 #ifdef __ANDROID__
 /**
  * initialize util client for android
@@ -115,6 +135,16 @@ CAResult_t CAUtilCreateBond(JNIEnv *env, jobject device);
  * @param[in]  listener         callback listener
  */
 void CAUtilSetFoundDeviceListener(jobject listener);
+
+/**
+ * set interval time and working count for LE scan.
+ * @param[in]  intervalTime         interval time(Seconds).
+ * @param[in]  workingCount         working cycle for selected interval time.
+ *
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
+ */
+CAResult_t CAUtilSetLEScanInterval(jint intervalTime, jint workingCount);
+
 #endif
 
 #ifdef __cplusplus
index e829d4b..4b71fd8 100644 (file)
@@ -8,7 +8,7 @@ import platform
 # Map of host os and allowed target os (host: allowed target os)
 host_target_map = {
                'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
-               'windows': ['windows', 'winrt', 'android', 'arduino'],
+               'windows': ['windows', 'android', 'arduino'],
                'darwin': ['darwin', 'ios', 'android', 'arduino'],
                }
 
@@ -18,7 +18,6 @@ os_arch_map = {
                'tizen': ['x86', 'x86_64', 'arm', 'arm64'],
                'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
                'windows': ['x86', 'amd64', 'arm'],
-               'winrt': ['arm'],
                'darwin': ['i386', 'x86_64'],
                'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
                'arduino': ['avr', 'arm'],
@@ -152,9 +151,9 @@ def __set_dir(env, dir):
                Exit(1)
 
        if env.get('RELEASE'):
-               build_dir = dir + '/out/' + target_os + '/' + target_arch + '/release/'
+               build_dir = os.path.join(dir, 'out', target_os, target_arch, 'release') + os.sep
        else:
-               build_dir = dir + '/out/' + target_os + '/' + target_arch + '/debug/'
+               build_dir = os.path.join(dir, 'out', target_os, target_arch, 'debug') + os.sep
        env.VariantDir(build_dir, dir, duplicate=0)
 
        env.Replace(BUILD_DIR = build_dir)
@@ -176,6 +175,9 @@ def __installlib(ienv, targets, name):
        if user_prefix:
                i_n = ienv.Install(user_prefix + '/lib', targets)
                ienv.Alias("install", i_n)
+       else:
+               i_n = ienv.Install(env.get('BUILD_DIR') + '/lib', targets)
+       ienv.Alias("install", i_n)
 
 def __installbin(ienv, targets, name):
        user_prefix = env.get('PREFIX')
index 1346ff9..ca56690 100644 (file)
@@ -4,8 +4,8 @@
 %define DEST_LIB_DIR  %{buildroot}/%{_libdir}
 
 Name: com-oic-ca
-Version:    0.1
-Release:    1
+Version:    1.1.1
+Release:    0
 Summary: Tizen oicca application
 URL: http://slp-source.sec.samsung.net
 Source: %{name}-%{version}.tar.gz
index 79326e5..4db7d47 100644 (file)
@@ -29,7 +29,7 @@ ca_common_src = [
                ca_common_src_path + 'caremotehandler.c'
        ]
 
-if env['POSIX_SUPPORTED']:
+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'
index d725980..08b1c1e 100644 (file)
 
 typedef struct _tagMutexInfo_t
 {
+#if defined(_MSC_VER)
+    uint8_t unused; //VS doesnt like empty structs
+#endif
 } ca_mutex_internal;
 
 typedef struct _tagEventInfo_t
 {
+#if defined(_MSC_VER)
+    uint8_t unused; //VS doesnt like empty structs
+#endif
 } ca_cond_internal;
 
 /**
@@ -57,7 +63,7 @@ static ca_cond_internal g_condInfo = { 0 };
 
 ca_mutex ca_mutex_new(void)
 {
-    return &g_mutexInfo;
+    return (ca_mutex)&g_mutexInfo;
 }
 
 bool ca_mutex_free(ca_mutex mutex)
@@ -77,7 +83,7 @@ void ca_mutex_unlock(ca_mutex mutex)
 
 ca_cond ca_cond_new(void)
 {
-    return &g_condInfo;
+    return (ca_cond)&g_condInfo;
 }
 
 void ca_cond_free(ca_cond cond)
index 834886c..6c166b1 100644 (file)
 #define _POSIX_C_SOURCE 200809L
 #endif
 
+#ifdef HAVE_STRING_H
 #include <string.h>
+#endif
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
-#include <errno.h>
+#endif
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_TIME_H
 #include <time.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"
 
@@ -76,13 +90,21 @@ 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;
 
 typedef struct _tagEventInfo_t
 {
+#if defined(_WIN32)
+    CONDITION_VARIABLE cond;
+#else
     pthread_cond_t cond;
     pthread_condattr_t condattr;
+#endif
 } ca_cond_internal;
 
 ca_mutex ca_mutex_new(void)
@@ -91,6 +113,10 @@ ca_mutex ca_mutex_new(void)
     ca_mutex_internal *mutexInfo = (ca_mutex_internal*) OICMalloc(sizeof(ca_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)
@@ -102,6 +128,11 @@ ca_mutex ca_mutex_new(void)
             OIC_LOG_V(ERROR, TAG, "%s Failed to initialize mutex !", __func__);
             OICFree(mutexInfo);
         }
+#endif
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Failed to allocate mutex!", __func__);
     }
 
     return retVal;
@@ -114,6 +145,11 @@ bool ca_mutex_free(ca_mutex mutex)
     ca_mutex_internal *mutexInfo = (ca_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)
         {
@@ -124,6 +160,7 @@ bool ca_mutex_free(ca_mutex mutex)
         {
             OIC_LOG_V(ERROR, TAG, "%s Failed to free mutex !", __func__);
         }
+#endif
     }
     else
     {
@@ -138,12 +175,16 @@ void ca_mutex_lock(ca_mutex mutex)
     ca_mutex_internal *mutexInfo = (ca_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
     {
@@ -157,6 +198,9 @@ void ca_mutex_unlock(ca_mutex mutex)
     ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
     if (mutexInfo)
     {
+#if defined(_WIN32)
+        LeaveCriticalSection(&mutexInfo->mutex);
+#else
         int ret = pthread_mutex_unlock(&mutexInfo->mutex);
         if(ret != 0)
         {
@@ -164,11 +208,12 @@ void ca_mutex_unlock(ca_mutex mutex)
             exit(ret);
         }
         (void)ret;
+#endif
     }
     else
     {
-          OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex !", __func__);
-          return;
+        OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex !", __func__);
+        return;
     }
 }
 
@@ -178,6 +223,10 @@ ca_cond ca_cond_new(void)
     ca_cond_internal *eventInfo = (ca_cond_internal*) OICMalloc(sizeof(ca_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)
         {
@@ -187,14 +236,15 @@ ca_cond ca_cond_new(void)
             return retVal;
         }
 
-#if defined(__ANDROID__) || _POSIX_TIMERS > 0
-#ifdef __ANDROID__
-        if (camutex_condattr_setclock) {
+ #if defined(__ANDROID__) || _POSIX_TIMERS > 0
+  #ifdef __ANDROID__
+        if (camutex_condattr_setclock)
+        {
             ret = camutex_condattr_setclock(&(eventInfo->condattr), CLOCK_MONOTONIC);
-#else
+  #else
         {
             ret = pthread_condattr_setclock(&(eventInfo->condattr), CLOCK_MONOTONIC);
-#endif /*  __ANDROID__ */
+  #endif /*  __ANDROID__ */
             if(0 != ret)
             {
                 OIC_LOG_V(ERROR, TAG, "%s: Failed to set condition variable clock %d!",
@@ -204,7 +254,7 @@ ca_cond ca_cond_new(void)
                 return retVal;
             }
         }
-#endif /* defined(__ANDROID__) || _POSIX_TIMERS > 0 */
+ #endif /* defined(__ANDROID__) || _POSIX_TIMERS > 0 */
         ret = pthread_cond_init(&(eventInfo->cond), &(eventInfo->condattr));
         if (0 == ret)
         {
@@ -216,6 +266,11 @@ ca_cond ca_cond_new(void)
             pthread_condattr_destroy(&(eventInfo->condattr));
             OICFree(eventInfo);
         }
+#endif
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Failed to allocate condition variable!", __func__);
     }
 
     return retVal;
@@ -226,6 +281,9 @@ void ca_cond_free(ca_cond cond)
     ca_cond_internal *eventInfo = (ca_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)
@@ -237,6 +295,7 @@ 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
     {
@@ -249,11 +308,15 @@ void ca_cond_signal(ca_cond cond)
     ca_cond_internal *eventInfo = (ca_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
     {
@@ -266,11 +329,15 @@ void ca_cond_broadcast(ca_cond cond)
     ca_cond_internal* eventInfo = (ca_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
     {
@@ -283,6 +350,14 @@ void ca_cond_wait(ca_cond cond, ca_mutex mutex)
     ca_cond_wait_for(cond, mutex, 0L);
 }
 
+#ifndef TIMEVAL_TO_TIMESPEC
+#define TIMEVAL_TO_TIMESPEC(tv, ts) {               \
+    (ts)->tv_sec = (tv)->tv_sec;                    \
+    (ts)->tv_nsec = (tv)->tv_usec * 1000;           \
+}
+#endif
+
+#if !defined(_WIN32)
 struct timespec ca_get_current_time()
 {
 #if defined(__ANDROID__) || _POSIX_TIMERS > 0
@@ -308,6 +383,7 @@ 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)
 {
@@ -330,11 +406,31 @@ CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseco
 
     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;
         struct timespec abstime;
 
 #ifdef __ANDROID__
-        if (camutex_cond_timedwait_relative) {
+        if (camutex_cond_timedwait_relative)
+        {
             abstime.tv_sec = microseconds / USECS_PER_SEC;
             abstime.tv_nsec = (microseconds % USECS_PER_SEC) * NANOSECS_PER_USECS;
             //Wait for the given time
@@ -367,14 +463,26 @@ CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseco
                 retVal = CA_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
     }
-
     return retVal;
 }
 
index 0fb57de..d17af9c 100644 (file)
 #define _GNU_SOURCE
 #endif
 #include <errno.h>
+#if defined HAVE_PTHREAD_H
 #include <pthread.h>
+#endif
+#if defined HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
 #include "cathreadpool.h"
 #include "logger.h"
 #include "oic_malloc.h"
 #include "uarraylist.h"
 #include "camutex.h"
+#include "platform_features.h"
 
 #define TAG PCF("UTHREADPOOL")
 
@@ -156,7 +162,6 @@ CAResult_t ca_thread_pool_add_task(ca_thread_pool_t thread_pool, ca_thread_func
     info->data = data;
 
     pthread_t threadHandle;
-
     int result = pthread_create(&threadHandle, NULL, ca_thread_pool_pthreads_delegate, info);
 
     if(result != 0)
@@ -194,11 +199,20 @@ void ca_thread_pool_free(ca_thread_pool_t thread_pool)
     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
     }
 
     u_arraylist_free(&(thread_pool->details->threads_list));
index d9f6e81..2e41cb9 100644 (file)
@@ -20,6 +20,7 @@
 #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"
index cd3f102..5f8c248 100644 (file)
 #include <jni.h>
 #endif
 
-#ifndef WITH_ARDUINO
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+
+#if defined(HAVE_WINSOCK2_H) && defined(HAVE_WS2TCPIP_H)
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
 
index a9463ab..05e7601 100644 (file)
@@ -65,12 +65,11 @@ typedef void (*CATCPErrorHandleCallback)(const CAEndpoint_t *endpoint, const voi
 /**
   * Callback to notify connection information in the TCP adapter.
   *
-  * @param[in]  addr    connected device address.
-  * @param[in]  port    connected port info.
-  * @param[in]  isConnected    Whether keepalive message needs to be sent.
+  * @param[in]  endpoint        network endpoint description.
+  * @param[in]  isConnected     Whether keepalive message needs to be sent.
   * @see  Callback must be registered using CATCPSetKeepAliveCallback().
  */
-typedef void (*CATCPConnectionHandleCallback)(const char *addr, uint16_t port, bool isConnected);
+typedef void (*CATCPConnectionHandleCallback)(const CAEndpoint_t *endpoint, bool isConnected);
 
 /**
  * set error callback to notify error in TCP adapter.
@@ -142,6 +141,13 @@ void CATCPStopServer();
 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback);
 
 /**
+ * Set this callback for receiving the changed connection information from peer devices.
+ *
+ * @param[in]  callback    Callback to be notified when connection state changes.
+ */
+void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler);
+
+/**
  * API to send unicast TCP data.
  *
  * @param[in]  endpoint          complete network address to send to.
index 3f2b93c..bef054c 100644 (file)
@@ -52,10 +52,10 @@ extern "C" {
  */
 #undef GET_SHA_256
 #define GET_SHA_256(tbs, sha256) do{                     \
-        DTLS_SHA256_CTX ctx256;                          \
-        DTLS_SHA256_Init(&ctx256);                       \
-        DTLS_SHA256_Update(&ctx256, tbs.data, tbs.len);  \
-        DTLS_SHA256_Final(sha256, &ctx256);              \
+        dtls_sha256_ctx ctx256;                          \
+        dtls_sha256_init(&ctx256);                       \
+        dtls_sha256_update(&ctx256, tbs.data, tbs.len);  \
+        dtls_sha256_final(sha256, &ctx256);              \
     }while(0)
 
 /**@def CHECK_SIGN(structure, caPubKey)
index 03713c5..b47c835 100644 (file)
@@ -29,14 +29,18 @@ if target_os == 'arduino':
                env.get('ARDUINO_HOME')+'/libraries/Ethernet/src/utility',
                ])
 
-if target_os not in ['arduino', 'windows', 'winrt']:
+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', 'winrt']:
+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'])
@@ -74,6 +78,6 @@ libcoap_src = [
        'block.c'
        ]
 
-libcoap = libcoap_env.StaticLibrary('libcoap', libcoap_src, OBJPREFIX='libcoap_')
+libcoap = libcoap_env.StaticLibrary('coap', libcoap_src, OBJPREFIX='libcoap_')
 
-libcoap_env.InstallTarget([libcoap], 'libcoap')
+libcoap_env.InstallTarget([libcoap], 'coap')
index bb44a99..c26784c 100644 (file)
 #include <sys/socket.h>
 #endif
 
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+
 #ifdef WITH_ARDUINO
 #define DEV_ADDR_SIZE_MAX (16)
 #endif
@@ -76,7 +84,7 @@ typedef struct coap_address_t
 
 #define _coap_is_mcast_impl(Address) uip_is_addr_mcast(&((Address)->addr))
 #endif /* WITH_CONTIKI */
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(_WIN32)
 
 /** multi-purpose address abstraction */
 typedef struct coap_address_t
@@ -91,7 +99,7 @@ typedef struct coap_address_t
     }addr;
 }coap_address_t;
 
-static inline int
+INLINE_API int
 _coap_address_equals_impl(const coap_address_t *a,
         const coap_address_t *b)
 {
@@ -116,7 +124,7 @@ _coap_address_equals_impl(const coap_address_t *a,
     return 0;
 }
 
-static inline int
+INLINE_API int
 _coap_is_mcast_impl(const coap_address_t *a)
 {
     if (!a)
@@ -143,7 +151,7 @@ typedef struct coap_address_t
     uint8_t      addr[DEV_ADDR_SIZE_MAX]; /**< device address. */
 } coap_address_t;
 
-static inline int
+INLINE_API int
 _coap_address_equals_impl(const coap_address_t *a,
                           const coap_address_t *b)
 {
@@ -163,7 +171,7 @@ _coap_address_equals_impl(const coap_address_t *a,
     return 1;
 }
 
-static inline int
+INLINE_API int
 _coap_is_mcast_impl(const coap_address_t *a)
 {
     if (!a)
@@ -182,7 +190,7 @@ _coap_is_mcast_impl(const coap_address_t *a)
  *
  * @param addr The coap_address_t object to initialize.
  */
-static inline void coap_address_init(coap_address_t *addr)
+INLINE_API void coap_address_init(coap_address_t *addr)
 {
     assert(addr);
     memset(addr, 0, sizeof(coap_address_t));
@@ -197,7 +205,7 @@ static inline void coap_address_init(coap_address_t *addr)
  * @c 1 if addresses are equal, @c 0 otherwise. The parameters @p a
  * and @p b must not be @c NULL;
  */
-static inline int coap_address_equals(const coap_address_t *a, const coap_address_t *b)
+INLINE_API int coap_address_equals(const coap_address_t *a, const coap_address_t *b)
 {
     assert(a);
     assert(b);
@@ -208,7 +216,7 @@ static inline int coap_address_equals(const coap_address_t *a, const coap_addres
  * Checks if given address @p a denotes a multicast address.  This
  * function returns @c 1 if @p a is multicast, @c 0 otherwise.
  */
-static inline int coap_is_mcast(const coap_address_t *a)
+INLINE_API int coap_is_mcast(const coap_address_t *a)
 {
     return a && _coap_is_mcast_impl(a);
 }
index 879cb38..0319827 100644 (file)
@@ -136,7 +136,7 @@ coap_async_state_t *coap_find_async(coap_context_t *context, coap_tid_t id);
  *
  * @param s The state object to update.
  */
-static inline void coap_touch_async(coap_async_state_t *s)
+INLINE_API void coap_touch_async(coap_async_state_t *s)
 {
     coap_ticks(&s->created);
 }
index 9add64f..3ac7fe1 100644 (file)
@@ -31,7 +31,7 @@
  *
  * @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise.
  */
-inline static int bits_setb(uint8_t *vec, size_t size, uint8_t bit)
+INLINE_API int bits_setb(uint8_t *vec, size_t size, uint8_t bit)
 {
     if (size <= (size_t)(bit >> 3))
         return -1;
@@ -51,7 +51,7 @@ inline static int bits_setb(uint8_t *vec, size_t size, uint8_t bit)
  *
  * @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise.
  */
-inline static int bits_clrb(uint8_t *vec, size_t size, uint8_t bit)
+INLINE_API int bits_clrb(uint8_t *vec, size_t size, uint8_t bit)
 {
     if (size <= (size_t)(bit >> 3))
         return -1;
@@ -70,7 +70,7 @@ inline static int bits_clrb(uint8_t *vec, size_t size, uint8_t bit)
  *
  * @return @c 1 if the bit is set, @c 0 otherwise.
  */
-inline static int bits_getb(const uint8_t *vec, size_t size, uint8_t bit)
+INLINE_API int bits_getb(const uint8_t *vec, size_t size, uint8_t bit)
 {
     if (size <= (size_t)(bit >> 3))
         return -1;
index 2d5ef07..bd660ef 100644 (file)
@@ -71,13 +71,13 @@ unsigned int coap_opt_block_num(const coap_opt_t *block_opt);
  * Checks if more than @p num blocks are required to deliver @p data_len
  * bytes of data for a block size of 1 << (@p szx + 4).
  */
-static inline int coap_more_blocks(size_t data_len, unsigned int num, unsigned short szx)
+INLINE_API int coap_more_blocks(size_t data_len, unsigned int num, unsigned short szx)
 {
     return ((num + 1) << (szx + 4)) < data_len;
 }
 
 /** Sets the More-bit in @p block_opt */
-static inline void coap_opt_block_set_m(coap_opt_t *block_opt, int m)
+INLINE_API void coap_opt_block_set_m(coap_opt_t *block_opt, int m)
 {
     if (m)
         *(COAP_OPT_VALUE(block_opt) + (COAP_OPT_LENGTH(block_opt) - 1)) |= 0x08;
index 6eb924b..64d1b26 100644 (file)
@@ -34,6 +34,9 @@ extern "C"
 #ifdef HAVE_TIME_H
 #include <time.h>
 #endif
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
 #ifdef WITH_LWIP
 
 #include <stdint.h>
@@ -44,12 +47,12 @@ extern "C"
 
     typedef uint32_t coap_tick_t;
 
-    static inline void coap_ticks_impl(coap_tick_t *t)
+    INLINE_API void coap_ticks_impl(coap_tick_t *t)
     {
         *t = sys_now();
     }
 
-    static inline void coap_clock_init_impl(void)
+    INLINE_API void coap_clock_init_impl(void)
     {
     }
 
@@ -75,7 +78,7 @@ extern "C"
     /** Set at startup to initialize the internal clock (time in seconds). */
     extern clock_time_t clock_offset;
 
-    static inline void
+    INLINE_API void
     contiki_clock_init_impl(void)
     {
         clock_init();
@@ -84,7 +87,7 @@ extern "C"
 
 #define coap_clock_init contiki_clock_init_impl
 
-    static inline void
+    INLINE_API void
     contiki_ticks_impl(coap_tick_t *t)
     {
         *t = clock_time();
@@ -93,7 +96,7 @@ extern "C"
 #define coap_ticks contiki_ticks_impl
 
 #endif /* WITH_CONTIKI */
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(_WIN32)
     typedef unsigned int coap_tick_t;
 
     /**
@@ -107,7 +110,7 @@ extern "C"
 
     /** Set at startup to initialize the internal clock (time in seconds). */
     extern time_t clock_offset;
-#endif /* WITH_POSIX */
+#endif /* WITH_POSIX || _WIN32 */
 
 #ifdef WITH_ARDUINO
 #include "Time.h"
@@ -134,7 +137,7 @@ extern time_t clock_offset;
 #endif /* WITH_ARDUINO */
 
 #ifndef coap_clock_init
-    static inline void coap_clock_init_impl(void)
+    INLINE_API void coap_clock_init_impl(void)
     {
 #ifdef HAVE_TIME_H
         clock_offset = time(NULL);
@@ -159,7 +162,7 @@ extern time_t clock_offset;
 #endif /* coap_clock_init */
 
 #ifndef coap_ticks
-    static inline void coap_ticks_impl(coap_tick_t *t)
+    INLINE_API void coap_ticks_impl(coap_tick_t *t)
     {
 #ifdef HAVE_SYS_TIME_H
         struct timeval tv;
@@ -176,7 +179,12 @@ extern time_t clock_offset;
 #endif
     *t = (tv - clock_offset) * COAP_TICKS_PER_SECOND;
 #  else
+#ifdef HAVE_TIME_H
+    time_t tv = time(NULL);
+    *t = difftime(tv, clock_offset) * COAP_TICKS_PER_SECOND;
+#else
 #    error "clock not implemented"
+#endif /* HAVE_TIME_H */
 #  endif /* WITH_ARDUINO */
 #endif /* HAVE_SYS_TIME_H */
 }
@@ -187,7 +195,7 @@ extern time_t clock_offset;
      * Returns @c 1 if and only if @p a is less than @p b where less is
      * defined on a signed data type.
      */
-    static inline
+    INLINE_API
     int coap_time_lt(coap_tick_t a, coap_tick_t b)
     {
         return ((coap_tick_diff_t)(a - b)) < 0;
@@ -197,7 +205,7 @@ extern time_t clock_offset;
      * Returns @c 1 if and only if @p a is less than or equal @p b where
      * less is defined on a signed data type.
      */
-    static inline
+    INLINE_API
     int coap_time_le(coap_tick_t a, coap_tick_t b)
     {
         return a == b || coap_time_lt(a, b);
index 71d396a..622e795 100644 (file)
@@ -4,11 +4,6 @@
 /* Define if building universal (internal helper macro) */
 /* #undef AC_APPLE_UNIVERSAL_BUILD */
 
-/* Define to 1 if you have the <arpa/inet.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_ARPA_INET_H 1
-#endif
-
 /* Define to 1 if you have the <assert.h> header file. */
 #define HAVE_ASSERT_H 1
 
 /* Define to 1 if you have the `memset' function. */
 #define HAVE_MEMSET 1
 
-/* Define to 1 if you have the <netdb.h> header file. */
-#define HAVE_NETDB_H 1
-
 /* Define to 1 if you have the <netinet/in.h> header file. */
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO) && !defined(_WIN32)
 #define HAVE_NETINET_IN_H 1
 #endif
 
 #define HAVE_STRRCHR 1
 
 /* Define to 1 if you have the <syslog.h> header file. */
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO) && !defined(_WIN32)
 #define HAVE_SYSLOG_H 1
 #endif
 
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_SOCKET_H 1
-#endif
-
 /* 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/time.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_TIME_H 1
+/* Define to 1 if you have the <sys/unistd.h> header file. */
+#if !defined(WITH_ARDUINO) && !defined(_WIN32)
+#define HAVE_SYS_UNISTD_H 1
 #endif
 
-/* Define to 1 if you have the <sys/types.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_TYPES_H 1
+/* Define to 1 if you have <Ws2tcpip.h> header file. */
+#if defined(_WIN32)
+#define HAVE_WS2TCPIP_H 1
 #endif
 
-/* Define to 1 if you have the <sys/unistd.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_UNISTD_H 1
+/* Define to 1 if you have <Winsock2.h> header file. */
+#if defined(_WIN32)
+#define HAVE_WINSOCK2_H 1
+#endif
+
+/* Define to 1 if you have <Windows.h> header file. */
+#if defined(_WIN32)
+#define HAVE_WINDOWS_H 1
 #endif
 
 /* Define to 1 if you have the <time.h> header file. */
 #endif
 
 /* Define to 1 if you have the <unistd.h> header file. */
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO) && !defined(_WIN32)
 #define HAVE_UNISTD_H 1
 #endif
 
 # endif
 #endif
 
+#ifndef INLINE_API
+#  if defined(__cplusplus)
+#    define INLINE_API inline
+#  else
+#    ifdef _MSC_VER
+#      define INLINE_API static __inline
+#    else
+#      define INLINE_API static inline
+#    endif
+#  endif
+#endif
+
 /* Define to rpl_malloc if the replacement function should be used. */
 /* #undef malloc */
 
index 027491d..fc4f1da 100644 (file)
@@ -53,7 +53,7 @@ static char *loglevels[] =
 
 #ifdef HAVE_TIME_H
 
-static inline 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);
@@ -63,7 +63,7 @@ static inline size_t print_timestamp(char *s, size_t len, coap_tick_t t)
 
 #else /* alternative implementation: just print the timestamp */
 
-static inline size_t
+INLINE_API size_t
 print_timestamp(char *s, size_t len, coap_tick_t t)
 {
 #ifdef HAVE_SNPRINTF
@@ -89,7 +89,7 @@ print_timestamp(char *s, size_t len, coap_tick_t t)
  *
  * @return The length of @p s.
  */
-static inline size_t
+INLINE_API size_t
 strnlen(const char *s, size_t maxlen)
 {
     size_t n = 0;
@@ -146,10 +146,12 @@ unsigned int print_readable(const unsigned char *data, unsigned int len, unsigne
 
 size_t coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, size_t len)
 {
-#ifdef HAVE_ARPA_INET_H
+#if defined(HAVE_ARPA_INET_H) || defined(_WIN32)
     const void *addrptr = NULL;
 #if defined(__ANDROID__)
     __uint16_t port;
+#elif defined(_WIN32)
+    uint16_t port;
 #else
     in_port_t port;
 #endif
@@ -194,7 +196,11 @@ size_t coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, si
             return 0;
     }
 
+#ifdef HAVE_SNPRINTF
     p += snprintf((char *) p, buf + len - p + 1, ":%d", port);
+#else /* HAVE_SNPRINTF */
+    /* @todo manual conversion of port number */
+#endif /* HAVE_SNPRINTF */
 
     return buf + len - p;
 #else /* HAVE_ARPA_INET_H */
index b1b2e57..a7a8888 100644 (file)
@@ -12,7 +12,7 @@
 #if (BSD >= 199103) || defined(WITH_CONTIKI)
 # include <string.h>
 #else
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO) && !defined(_MSC_VER)
 # include <strings.h>
 #endif
 #endif
index 580729b..48e0455 100644 (file)
 #ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
+#ifdef _WIN32
+#define ssize_t SSIZE_T
+#endif
 #ifdef HAVE_NETINET_IN_H
 #include <netinet/in.h>
 #endif
 #ifdef HAVE_ARPA_INET_H
 #include <arpa/inet.h>
 #endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
 
 #ifdef WITH_LWIP
 #include <lwip/pbuf.h>
 #include "block.h"
 #include "net.h"
 
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
 
 time_t clock_offset=0;
 
-static inline coap_queue_t *
+INLINE_API coap_queue_t *
 coap_malloc_node()
 {
     return (coap_queue_t *)coap_malloc(sizeof(coap_queue_t));
 }
 
-static inline void
+INLINE_API void
 coap_free_node(coap_queue_t *node)
 {
     coap_free(node);
@@ -70,13 +79,13 @@ coap_free_node(coap_queue_t *node)
 static void coap_retransmittimer_execute(void *arg);
 static void coap_retransmittimer_restart(coap_context_t *ctx);
 
-static inline coap_queue_t *
+INLINE_API coap_queue_t *
 coap_malloc_node()
 {
     return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE);
 }
 
-static inline void
+INLINE_API void
 coap_free_node(coap_queue_t *node)
 {
     memp_free(MEMP_COAP_NODE, node);
@@ -106,13 +115,13 @@ MEMB(node_storage, coap_queue_t, COAP_PDU_MAXCNT);
 
 PROCESS(coap_retransmit_process, "message retransmit process");
 
-static inline coap_queue_t *
+INLINE_API coap_queue_t *
 coap_malloc_node()
 {
     return (coap_queue_t *)memb_alloc(&node_storage);
 }
 
-static inline void
+INLINE_API void
 coap_free_node(coap_queue_t *node)
 {
     memb_free(&node_storage, node);
@@ -321,7 +330,7 @@ is_wkc(coap_key_t k)
 coap_context_t *
 coap_new_context(const coap_address_t *listen_addr)
 {
-#if defined(WITH_POSIX)
+#if defined(WITH_POSIX) || defined(_WIN32)
     coap_context_t *c = coap_malloc( sizeof( coap_context_t ) );
     int reuse = 1;
 #elif WITH_CONTIKI
@@ -386,7 +395,7 @@ coap_new_context(const coap_address_t *listen_addr)
     coap_register_option(c, COAP_OPTION_BLOCK2);
     coap_register_option(c, COAP_OPTION_BLOCK1);
 
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
     c->sockfd = socket(listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0);
     if ( c->sockfd < 0 )
     {
@@ -396,7 +405,7 @@ coap_new_context(const coap_address_t *listen_addr)
         goto onerror;
     }
 
-    if ( setsockopt( c->sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse) ) < 0 )
+    if ( setsockopt( c->sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse) ) < 0 )
     {
 #ifndef NDEBUG
         coap_log(LOG_WARNING, "setsockopt SO_REUSEADDR\n");
@@ -451,7 +460,7 @@ coap_new_context(const coap_address_t *listen_addr)
 
 void coap_free_context(coap_context_t *context)
 {
-#if defined(WITH_POSIX) || defined(WITH_LWIP)
+#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(_WIN32)
     coap_resource_t *res;
 #ifndef COAP_RESOURCES_NOHASH
     coap_resource_t *rtmp;
@@ -468,7 +477,7 @@ void coap_free_context(coap_context_t *context)
     coap_retransmittimer_restart(context);
 #endif
 
-#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO) || defined(_WIN32)
 #ifdef COAP_RESOURCES_NOHASH
     LL_FOREACH(context->resources, res)
     {
@@ -480,7 +489,7 @@ void coap_free_context(coap_context_t *context)
         }
 #endif /* WITH_POSIX || WITH_LWIP */
 
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(_WIN32)
     /* coap_delete_list(context->subscriptions); */
     close( context->sockfd );
     coap_free( context );
@@ -538,7 +547,7 @@ void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu, coap
     /* Compare the complete address structure in case of IPv4. For IPv6,
      * we need to look at the transport address only. */
 
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(_WIN32)
     switch (peer->addr.sa.sa_family)
     {
         case AF_INET:
@@ -598,7 +607,7 @@ coap_send_impl(coap_context_t *context,
 }
 #endif
 
-#if defined(WITH_POSIX)
+#if defined(WITH_POSIX) || defined(_WIN32)
 /* releases space allocated by PDU if free_pdu is set */
 coap_tid_t
 coap_send_impl(coap_context_t *context,
@@ -611,7 +620,7 @@ coap_send_impl(coap_context_t *context,
     if ( !context || !dst || !pdu )
     return id;
 
-    bytes_written = sendto( context->sockfd, pdu->hdr, pdu->length, 0,
+    bytes_written = sendto( context->sockfd, (char*)pdu->hdr, pdu->length, 0,
             &dst->addr.sa, dst->size);
 
     if (bytes_written >= 0)
@@ -879,7 +888,7 @@ coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
  * This function returns @c 1 on success, or @c 0 if the option @p opt
  * would exceed @p maxpos.
  */
-static inline int check_opt_size(coap_opt_t *opt, unsigned char *maxpos)
+INLINE_API int check_opt_size(coap_opt_t *opt, unsigned char *maxpos)
 {
     if (opt && opt < maxpos)
     {
@@ -892,7 +901,7 @@ static inline int check_opt_size(coap_opt_t *opt, unsigned char *maxpos)
 #ifndef WITH_ARDUINO
 int coap_read(coap_context_t *ctx)
 {
-#if defined(WITH_POSIX)
+#if defined(WITH_POSIX) || defined(_WIN32)
     static char buf[COAP_MAX_PDU_SIZE];
 #endif
 #if defined(WITH_LWIP) || defined(WITH_CONTIKI)
@@ -916,7 +925,7 @@ int coap_read(coap_context_t *ctx)
 
     coap_address_init(&src);
 
-#if defined(WITH_POSIX)
+#if defined(WITH_POSIX) || defined(_WIN32)
     bytes_read = recvfrom(ctx->sockfd, buf, sizeof(buf), 0, &src.addr.sa, &src.size);
 
 #endif /* WITH_POSIX || WITH_ARDUINO */
@@ -1067,7 +1076,7 @@ int coap_remove_from_queue(coap_queue_t **queue, coap_tid_t id, coap_queue_t **n
 
 }
 
-static inline int token_match(const unsigned char *a, size_t alen, const unsigned char *b,
+INLINE_API int token_match(const unsigned char *a, size_t alen, const unsigned char *b,
         size_t blen)
 {
     return alen == blen && (alen == 0 || memcmp(a, b, alen) == 0);
@@ -1229,7 +1238,7 @@ coap_new_error_response(coap_pdu_t *request, unsigned char code, coap_opt_filter
  * Quick hack to determine the size of the resource description for
  * .well-known/core.
  */
-static inline size_t get_wkc_len(coap_context_t *context, coap_opt_t *query_filter)
+INLINE_API size_t get_wkc_len(coap_context_t *context, coap_opt_t *query_filter)
 {
     unsigned char buf[1];
     size_t len = 0;
@@ -1504,7 +1513,7 @@ void handle_request(coap_context_t *context, coap_queue_t *node, const char* res
     }
 }
 
-static inline void handle_response(coap_context_t *context, coap_queue_t *sent, coap_queue_t *rcvd)
+INLINE_API void handle_response(coap_context_t *context, coap_queue_t *sent, coap_queue_t *rcvd)
 {
 
     /* Call application-specific reponse handler when available.  If
@@ -1522,7 +1531,7 @@ static inline void handle_response(coap_context_t *context, coap_queue_t *sent,
     }
 }
 
-static inline int
+INLINE_API int
 #ifdef __GNUC__
 handle_locally(coap_context_t *context __attribute__ ((unused)),
         coap_queue_t *node __attribute__ ((unused)))
index 6e71da8..bd86b19 100644 (file)
@@ -113,7 +113,7 @@ extern "C"
      * to sendqueue_basetime. */
     coap_tick_t sendqueue_basetime;
     coap_queue_t *sendqueue, *recvqueue;
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
     int sockfd; /**< send/receive socket */
 #endif /* WITH_POSIX || WITH_ARDUINO */
 #ifdef WITH_CONTIKI
@@ -155,7 +155,7 @@ extern "C"
      * @param context The context to register the handler for.
      * @param handler The response handler to register.
      */
-    static inline void coap_register_response_handler(coap_context_t *context,
+    INLINE_API void coap_register_response_handler(coap_context_t *context,
             coap_response_handler_t handler)
     {
         context->response_handler = handler;
@@ -168,7 +168,7 @@ extern "C"
      * @param ctx  The context to use.
      * @param type The option type to register.
      */
-    inline static void coap_register_option(coap_context_t *ctx, unsigned char type)
+    INLINE_API void coap_register_option(coap_context_t *ctx, unsigned char type)
     {
         coap_option_setb(ctx->known_options, type);
     }
@@ -197,7 +197,7 @@ extern "C"
  * @param context the current coap_context_t object
  * @return incremented message id in network byte order
  */
-static inline unsigned short coap_new_message_id(coap_context_t *context)
+INLINE_API unsigned short coap_new_message_id(coap_context_t *context)
 {
     ++(context->message_id);
 #if defined(WITH_ARDUINO)
@@ -317,7 +317,7 @@ static inline unsigned short coap_new_message_id(coap_context_t *context)
      * @return The transaction id if RST was sent or @c COAP_INVALID_TID
      * on error.
      */
-    static inline coap_tid_t coap_send_rst(coap_context_t *context, const coap_address_t *dst,
+    INLINE_API coap_tid_t coap_send_rst(coap_context_t *context, const coap_address_t *dst,
             coap_pdu_t *request)
     {
         return coap_send_message_type(context, dst, request, COAP_MESSAGE_RST);
@@ -372,7 +372,7 @@ static inline unsigned short coap_new_message_id(coap_context_t *context)
      *
      * @return @c 1 if node was found, removed and destroyed, @c 0 otherwise.
      */
-    inline static int coap_remove_transaction(coap_queue_t **queue, coap_tid_t id)
+    INLINE_API int coap_remove_transaction(coap_queue_t **queue, coap_tid_t id)
     {
         coap_queue_t *node;
         if (!coap_remove_from_queue(queue, id, &node))
index ea60aab..60bb865 100644 (file)
@@ -208,7 +208,7 @@ coap_option_iterator_init(coap_pdu_t *pdu, coap_opt_iterator_t *oi,
     return oi;
 }
 
-static inline int opt_finished(coap_opt_iterator_t *oi)
+INLINE_API int opt_finished(coap_opt_iterator_t *oi)
 {
     assert(oi);
 
index 9c33ac8..8441d5a 100644 (file)
@@ -112,7 +112,7 @@ typedef unsigned char coap_opt_filter_t[(COAP_MAX_OPT >> 3) + 1];
  *
  * @param f The filter to clear.
  */
-static inline void coap_option_filter_clear(coap_opt_filter_t f)
+INLINE_API void coap_option_filter_clear(coap_opt_filter_t f)
 {
     memset(f, 0, sizeof(coap_opt_filter_t));
 }
@@ -127,7 +127,7 @@ static inline void coap_option_filter_clear(coap_opt_filter_t f)
  *
  * @return @c 1 if bit was set, @c -1 otherwise.
  */
-inline static int coap_option_setb(coap_opt_filter_t filter, unsigned short type)
+INLINE_API int coap_option_setb(coap_opt_filter_t filter, unsigned short type)
 {
     return bits_setb((uint8_t *) filter, sizeof(coap_opt_filter_t), type);
 }
@@ -142,7 +142,7 @@ inline static int coap_option_setb(coap_opt_filter_t filter, unsigned short type
  *
  * @return @c 1 if bit was set, @c -1 otherwise.
  */
-inline static int coap_option_clrb(coap_opt_filter_t filter, unsigned short type)
+INLINE_API int coap_option_clrb(coap_opt_filter_t filter, unsigned short type)
 {
     return bits_clrb((uint8_t *) filter, sizeof(coap_opt_filter_t), type);
 }
@@ -157,7 +157,7 @@ inline static int coap_option_clrb(coap_opt_filter_t filter, unsigned short type
  *
  * @return @c 1 if bit was set, @c 0 if not, @c -1 on error.
  */
-inline static int coap_option_getb(const coap_opt_filter_t filter, unsigned short type)
+INLINE_API int coap_option_getb(const coap_opt_filter_t filter, unsigned short type)
 {
     return bits_getb((uint8_t *) filter, sizeof(coap_opt_filter_t), type);
 }
index 1b36674..c6efa8d 100644 (file)
@@ -19,6 +19,9 @@
 #ifdef HAVE_ARPA_INET_H
 #include <arpa/inet.h>
 #endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
 
 #include "debug.h"
 #include "pdu.h"
@@ -137,7 +140,7 @@ coap_pdu_init(unsigned char type, unsigned char code, unsigned short id,
 #endif
 
     /* size must be large enough for hdr */
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
     pdu = (coap_pdu_t *) coap_malloc(sizeof(coap_pdu_t) + size);
 #endif
 #ifdef WITH_CONTIKI
@@ -275,7 +278,7 @@ coap_transport_type coap_get_tcp_header_type_from_size(unsigned int size)
     {
         return coap_tcp_16bit;
     }
-    else if (size < ULONG_MAX + COAP_TCP_LENGTH_FIELD_32_BIT)
+    else if (size - COAP_TCP_LENGTH_FIELD_32_BIT < ULONG_MAX)
     {
         return coap_tcp_32bit;
     }
index c375416..34b1b5c 100644 (file)
@@ -234,10 +234,10 @@ typedef union
 {
     struct
     {
-        unsigned int token_length :4; /* length of Token */
-        unsigned int type :2; /* type flag */
-        unsigned int version :2; /* protocol version */
-        unsigned int code :8; /* request method (value 1--10) or response code (value 40-255) */
+        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;
index 25e7720..8e2b85b 100644 (file)
@@ -29,7 +29,7 @@
  * implementation for prng().  You might want to change prng() to use
  * a better PRNG on your specific platform.
  */
-static inline int coap_prng_impl(unsigned char *buf, size_t len)
+INLINE_API int coap_prng_impl(unsigned char *buf, size_t len)
 {
     while (len--)
         *buf++ = rand() & 0xFF;
@@ -43,7 +43,7 @@ static inline int coap_prng_impl(unsigned char *buf, size_t len)
  * implementation for prng().  You might want to change prng() to use
  * a better PRNG on your specific platform.
  */
-static inline int
+INLINE_API int
 contiki_prng_impl(unsigned char *buf, size_t len)
 {
     unsigned short v = random_rand();
index 3954517..3af2f0c 100644 (file)
@@ -27,7 +27,7 @@
 #define COAP_FREE_TYPE(Type, Object) memp_free(MEMP_COAP_##Type, Object)
 
 #endif
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
 #include "utlist.h"
 #include "mem.h"
 
@@ -64,7 +64,9 @@ coap_free_subscription(coap_subscription_t *subscription)
 }
 #endif /* WITH_CONTIKI */
 
+#ifndef min
 #define min(a,b) ((a) < (b) ? (a) : (b))
+#endif
 
 /* Helper functions for conditional output of character sequences into
  * a given buffer. The first Offset characters are skipped.
@@ -339,7 +341,7 @@ coap_resource_init(const unsigned char *uri, size_t len, int flags)
 {
     coap_resource_t *r;
 
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
     r = (coap_resource_t *)coap_malloc(sizeof(coap_resource_t));
 #endif
 #ifdef WITH_LWIP
@@ -381,7 +383,7 @@ coap_add_attr(coap_resource_t *resource, const unsigned char *name, size_t nlen,
     if (!resource || !name)
         return NULL;
 
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
     attr = (coap_attr_t *)coap_malloc(sizeof(coap_attr_t));
 #endif
 #ifdef WITH_LWIP
@@ -501,7 +503,7 @@ int coap_delete_resource(coap_context_t *context, coap_key_t key)
     if (!resource)
         return 0;
 
-#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO) || defined(_WIN32)
 #ifdef COAP_RESOURCES_NOHASH
     LL_DELETE(context->resources, resource);
 #else
@@ -514,7 +516,7 @@ int coap_delete_resource(coap_context_t *context, coap_key_t key)
     if (resource->flags & COAP_RESOURCE_FLAGS_RELEASE_URI)
         coap_free(resource->uri.s);
 
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
     coap_free(resource);
 #endif
 #ifdef WITH_LWIP
index 9382615..2349be1 100644 (file)
@@ -220,7 +220,7 @@ coap_print_status_t coap_print_link(const coap_resource_t *resource, unsigned ch
  * @param method   The CoAP request method to handle.
  * @param handler  The handler to register with @p resource.
  */
-static inline void coap_register_handler(coap_resource_t *resource, unsigned char method,
+INLINE_API void coap_register_handler(coap_resource_t *resource, unsigned char method,
         coap_method_handler_t handler)
 {
     assert(resource);
index 5f25f96..60fb972 100644 (file)
@@ -91,30 +91,30 @@ struct list
     (struct_ptr)->LIST_CONCAT(name,_list) = NULL;           \
   }
 
-static inline void *
+INLINE_API void *
 list_head(list_t the_list)
 {
     return *the_list;
 }
 
-static inline void list_remove(list_t the_list, void *item)
+INLINE_API void list_remove(list_t the_list, void *item)
 {
     if (list_head(the_list))
         LL_DELETE(*(struct list **)the_list, (struct list *)item);
 }
 
-static inline void list_add(list_t the_list, void *item)
+INLINE_API void list_add(list_t the_list, void *item)
 {
     list_remove(the_list, item);
     LL_APPEND(*(struct list **)the_list, (struct list *)item);
 }
 
-static inline void list_push(list_t the_list, void *item)
+INLINE_API void list_push(list_t the_list, void *item)
 {
     LL_PREPEND(*(struct list **)the_list, (struct list *)item);
 }
 
-static inline void *
+INLINE_API void *
 list_pop(list_t the_list)
 {
     struct list *l;
@@ -125,7 +125,7 @@ list_pop(list_t the_list)
     return l;
 }
 
-static inline void list_insert(list_t the_list, void *previtem, void *newitem)
+INLINE_API void list_insert(list_t the_list, void *previtem, void *newitem)
 {
     if (previtem == NULL)
     {
@@ -138,7 +138,7 @@ static inline void list_insert(list_t the_list, void *previtem, void *newitem)
     }
 }
 
-static inline void *
+INLINE_API void *
 list_item_next(void *item)
 {
     return item == NULL ? NULL : ((struct list *) item)->next;
index 42dab60..d496e72 100644 (file)
@@ -32,7 +32,7 @@
  * @return A pointer to the first occurence of @p c, or @c NULL
  * if not found.
  */
-static inline unsigned char *
+INLINE_API unsigned char *
 strnchr(unsigned char *s, size_t len, unsigned char c)
 {
     while (len && *s++ != c)
@@ -493,7 +493,7 @@ coap_clone_uri(const coap_uri_t *uri)
 
 /* The function signature of coap_hash() is different from
  * segment_handler_t hence we use this wrapper as safe typecast. */
-static inline void hash_segment(unsigned char *s, size_t len, void *data)
+INLINE_API void hash_segment(unsigned char *s, size_t len, void *data)
 {
     coap_hash(s, len, (unsigned char *) data);
 }
index a1c739c..1889a8e 100644 (file)
@@ -62,7 +62,7 @@
  when compiling c++ code), this code uses whatever method is needed
  or, for VS2008 where neither is available, uses casting workarounds. */
 #ifdef _MSC_VER            /* MS compiler */
-#if _MSC_VER >= 1600 && __cplusplus  /* VS2010 and newer in C++ mode */
+#if (_MSC_VER >= 1600) && (defined(__cplusplus) && (__cplusplus >= 201103L))  /* VS2010 and newer in C++ mode */
 #define LDECLTYPE(x) decltype(x)
 #else                     /* VS2008 or older (or VS2010 in C mode) */
 #define NO_DECLTYPE
@@ -338,11 +338,11 @@ do {
     (head)=(head)->next;                                                                       \
   } else {                                                                                     \
     char *_tmp = (char*)(head);                                                                \
-    while (head->next && (head->next != (del))) {                                              \
-      head = head->next;                                                                       \
+    while ((head)->next && ((head)->next != (del))) {                                          \
+      (head) = (head)->next;                                                                   \
     }                                                                                          \
-    if (head->next) {                                                                          \
-      head->next = ((del)->next);                                                              \
+    if ((head)->next) {                                                                        \
+      (head)->next = ((del)->next);                                                            \
     }                                                                                          \
     {                                                                                          \
       char **_head_alias = (char**)&(head);                                                    \
index 3c671a3..d2b52e8 100644 (file)
@@ -23,40 +23,34 @@ print"Reading ca script %s"%ca_transport
 
 env.PrependUnique(CPPPATH = [ os.path.join(root_dir, 'api') ])
 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') ])
+                             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') ])
 
-if ca_os not in ['arduino', 'windows', 'winrt']:
+if ca_os not in ['arduino', 'windows']:
        env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
 
-if ca_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if ca_os not in ['darwin', 'ios', 'windows']:
        env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
 
 if ca_os in ['darwin','ios']:
        env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
 
 # Getting common source files
-env.SConscript('./../common/SConscript')
+env.SConscript(os.path.join(root_dir, 'common', 'SConscript'))
 
 # Getting util source files
-env.SConscript(root_dir + '/util/SConscript')
+env.SConscript(os.path.join(root_dir, 'util', 'SConscript'))
 
 # The tinydtls library is found in '#extlibs/tinydtls', where the '#'
 # is interpreted by SCons as the top-level iotivity directory where
 # the SConscruct file is found.
+build_dir = env.get('BUILD_DIR')
 if env.get('SECURED') == '1':
-       if ca_os == 'tizen' and os.path.exists(root_dir + '/extlibs/tinydtls'):
-               env.SConscript(os.path.join(root_dir, 'extlibs/tinydtls/SConscript'))
-       else:
-               env.SConscript('#extlibs/tinydtls/SConscript')
-       if ca_os == 'tizen' and os.path.exists(root_dir + '/extlibs/timer'):
-               env.SConscript(os.path.join(root_dir, 'extlibs/timer/SConscript'))
-               env.AppendUnique(CPPPATH = [os.path.join(root_dir, 'extlibs/timer')])
-       else:
-               env.SConscript('#extlibs/timer/SConscript')
-               env.AppendUnique(CPPPATH = ['#extlibs/timer'])
+       env.SConscript(build_dir + 'extlibs/tinydtls/SConscript')
+       env.SConscript(build_dir + 'extlibs/timer/SConscript')
+       env.AppendUnique(CPPPATH = ['#extlibs/timer'])
 
 env.AppendUnique(CA_SRC = [os.path.join(ca_path,
                                         'adapter_util/caadapterutils.c')])
@@ -157,11 +151,14 @@ if ca_os in ['linux', 'tizen', 'android', 'arduino', 'ios']:
 
 print "Include path is %s" % env.get('CPPPATH')
 print "Files path is %s" % env.get('CA_SRC')
-               
+
 lib_env = env.Clone()
 
+if env.get('LOGGING'):
+       lib_env.AppendUnique(CPPDEFINES=['TB_LOG'])
+
 if ca_os == 'android':
-    lib_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,libconnectivity_abstraction.so'])
+       lib_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,libconnectivity_abstraction.so'])
 
 if ca_os in ['android', 'tizen']:
        lib_env.AppendUnique(LIBS = ['coap'])
@@ -170,8 +167,14 @@ if ca_os in ['android', 'tizen']:
                lib_env.AppendUnique(LIBS = ['timer'])
        if ca_os != 'android':
                lib_env.AppendUnique(LIBS = ['rt'])
-       calib = lib_env.SharedLibrary('connectivity_abstraction', lib_env.get('CA_SRC'))
+       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'])
+       if lib_env.get('SECURED') == '1':
+               lib_env.AppendUnique(LIBS = ['tinydtls'])
+               lib_env.AppendUnique(LIBS = ['timer'])
+       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, 'libconnectivity_abstraction')
-lib_env.UserInstallTargetLib(calib, 'libconnectivity_abstraction')
+lib_env.InstallTarget(calib, 'connectivity_abstraction')
+lib_env.UserInstallTargetLib(calib, 'connectivity_abstraction')
index 8caf45f..6ca39de 100644 (file)
 #include "oic_string.h"
 #include "global.h"
 #include "timer.h"
+#if defined(HAVE_WINSOCK2_H) && defined(HAVE_WS2TCPIP_H)
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_NETDB_H
 #include <netdb.h>
+#endif
 
 /* tinyDTLS library error code */
 #define TINY_DTLS_ERROR (-1)
@@ -71,10 +77,10 @@ static ca_mutex g_dtlsContextMutex = NULL;
 static CAGetDTLSPskCredentialsHandler g_getCredentialsCallback = NULL;
 
 /**
- * @var MAX_RETRANSMISSION_TIME
+ * @var RETRANSMISSION_TIME
  * @brief Maximum timeout value (in seconds) to start DTLS retransmission.
  */
-#define MAX_RETRANSMISSION_TIME 1
+#define RETRANSMISSION_TIME 1
 
 /**
  * @var g_dtlsHandshakeCallback
@@ -491,7 +497,7 @@ static int32_t CASendSecureData(dtls_context_t *context,
     endpoint.flags = addrInfo->addr.st.ss_family == AF_INET ? CA_IPV4 : CA_IPV6;
     endpoint.flags |= CA_SECURE;
     endpoint.adapter = CA_ADAPTER_IP;
-    endpoint.interface = session->ifindex;
+    endpoint.ifindex = session->ifindex;
     int type = 0;
 
     //Mutex is not required for g_caDtlsContext. It will be called in same thread.
@@ -554,14 +560,14 @@ static int32_t CAHandleSecureEvent(dtls_context_t *context,
             g_dtlsHandshakeCallback(&endpoint, &errorInfo);
         }
     }
-    else if(DTLS_ALERT_LEVEL_FATAL == level && DTLS_ALERT_CLOSE_NOTIFY == code)
+    else if(DTLS_ALERT_LEVEL_FATAL == level && DTLS_ALERT_HANDSHAKE_FAILURE == code)
     {
-        OIC_LOG(INFO, NET_DTLS_TAG, "Peer closing connection");
+        OIC_LOG(INFO, NET_DTLS_TAG, "Failed to DTLS handshake, the peer will be removed.");
         CARemovePeerFromPeerInfoList(peerAddr, port);
     }
-    else if(DTLS_ALERT_LEVEL_FATAL == level && DTLS_ALERT_HANDSHAKE_FAILURE == code)
+    else if(DTLS_ALERT_LEVEL_FATAL == level || DTLS_ALERT_CLOSE_NOTIFY == code)
     {
-        OIC_LOG(INFO, NET_DTLS_TAG, "Failed to DTLS handshake, the peer will be removed.");
+        OIC_LOG(INFO, NET_DTLS_TAG, "Peer closing connection");
         CARemovePeerFromPeerInfoList(peerAddr, port);
     }
 
@@ -838,7 +844,7 @@ int CAInitX509()
     {
         uint8_t crlData[CRL_MAX_LEN] = {0};
         ByteArray crlArray = {crlData, CRL_MAX_LEN};
-        g_getCrlCallback(crlArray);
+        g_getCrlCallback(&crlArray);
         if (crlArray.len > 0)
         {
             uint8_t keyData[PUBLIC_KEY_SIZE] = {0};
@@ -1013,10 +1019,6 @@ exit:
 static void CAStartRetransmit()
 {
     static int timerId = -1;
-    clock_time_t nextSchedule = MAX_RETRANSMISSION_TIME;
-
-    OIC_LOG(DEBUG, NET_DTLS_TAG, "CAStartRetransmit IN");
-
     if (timerId != -1)
     {
         //clear previous timer
@@ -1031,25 +1033,11 @@ static void CAStartRetransmit()
             ca_mutex_unlock(g_dtlsContextMutex);
             return;
         }
-
-        OIC_LOG(DEBUG, NET_DTLS_TAG, "Check retransmission");
-        dtls_check_retransmit(g_caDtlsContext->dtlsContext, &nextSchedule);
+        dtls_check_retransmit(g_caDtlsContext->dtlsContext, NULL);
         ca_mutex_unlock(g_dtlsContextMutex);
-
-        //re-transmission timeout should not be greater then max one
-        //this will cover case when several clients start dtls sessions
-        nextSchedule /= CLOCKS_PER_SEC;
-        if (nextSchedule > MAX_RETRANSMISSION_TIME)
-        {
-            nextSchedule = MAX_RETRANSMISSION_TIME;
-        }
     }
-
     //start new timer
-    OIC_LOG(DEBUG, NET_DTLS_TAG, "Start new timer");
-    registerTimer(nextSchedule, &timerId, CAStartRetransmit);
-
-    OIC_LOG(DEBUG, NET_DTLS_TAG, "CAStartRetransmit OUT");
+    registerTimer(RETRANSMISSION_TIME, &timerId, CAStartRetransmit);
 }
 
 CAResult_t CAAdapterNetDtlsInit()
index 83f24eb..9ddc7e8 100644 (file)
 #include "oic_malloc.h"
 #include <errno.h>
 
-#ifndef WITH_ARDUINO
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
 #include <netinet/in.h>
+#endif
+#if defined(HAVE_WINSOCK2_H) && defined(HAVE_WS2TCPIP_H)
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_NETDB_H
 #include <netdb.h>
 #endif
 
@@ -137,6 +148,7 @@ void CAConvertAddrToName(const struct sockaddr_storage *sockAddr, socklen_t sock
                         NI_NUMERICHOST|NI_NUMERICSERV);
     if (r)
     {
+#if defined(EAI_SYSTEM)
         if (EAI_SYSTEM == r)
         {
             OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
@@ -147,6 +159,13 @@ void CAConvertAddrToName(const struct sockaddr_storage *sockAddr, socklen_t sock
             OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
                             "getnameinfo failed: %s", gai_strerror(r));
         }
+#elif defined(_WIN32)
+        OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+                            "getnameinfo failed: errno %i", WSAGetLastError());
+#else
+        OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+                            "getnameinfo failed: %s", gai_strerror(r));
+#endif
         return;
     }
     *port = ntohs(((struct sockaddr_in *)sockAddr)->sin_port); // IPv4 and IPv6
@@ -165,6 +184,7 @@ void CAConvertNameToAddr(const char *host, uint16_t port, struct sockaddr_storag
     int r = getaddrinfo(host, NULL, &hints, &addrs);
     if (r)
     {
+#if defined(EAI_SYSTEM)
         if (EAI_SYSTEM == r)
         {
             OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
@@ -175,6 +195,13 @@ void CAConvertNameToAddr(const char *host, uint16_t port, struct sockaddr_storag
             OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
                             "getaddrinfo failed: %s", gai_strerror(r));
         }
+#elif defined(_WIN32)
+        OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+                            "getaddrinfo failed: errno %i", WSAGetLastError());
+#else
+        OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+                            "getaddrinfo failed: %s", gai_strerror(r));
+#endif
         return;
     }
     // assumption: in this case, getaddrinfo will only return one addrinfo
index bdcc44e..6a674ae 100644 (file)
@@ -210,7 +210,7 @@ CAResult_t CAEDRGetAdapterEnableState(bool *state)
         return CA_STATUS_INVALID_PARAM;
     }
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -249,7 +249,7 @@ void CAEDRJniInitContext()
 
 CAResult_t CAEDRCreateJNIInterfaceObject(jobject context)
 {
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     OIC_LOG(DEBUG, TAG, "CAEDRCreateJNIInterfaceObject");
 
     if ((*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
@@ -353,7 +353,7 @@ CAResult_t CAEDRInitialize()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -404,7 +404,7 @@ void CAEDRTerminate()
     OIC_LOG(DEBUG, TAG, "CAEDRTerminate");
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -451,7 +451,7 @@ CAResult_t CAEDRDestroyJniInterface()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -531,7 +531,7 @@ CAResult_t CAEDRSendMulticastMessage(const uint8_t* data, uint32_t dataLen)
     VERIFY_NON_NULL(data, TAG, "data is null");
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -572,7 +572,7 @@ CAResult_t CAEDRGetInterfaceInfo(char **address)
 void CAEDRGetLocalAddress(char **address)
 {
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -619,7 +619,7 @@ CAResult_t CAEDRSendUnicastMessageImpl(const char* address, const uint8_t* data,
     VERIFY_NON_NULL(data, TAG, "data is null");
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
index 3d4dcb6..b1cf8a0 100644 (file)
@@ -118,7 +118,7 @@ static void CAReceiveHandler(void *data)
     VERIFY_NON_NULL_VOID(data, TAG, "Invalid thread context");
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -172,7 +172,7 @@ static void CAAcceptHandler(void *data)
     VERIFY_NON_NULL_VOID(data, TAG, "data is null");
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -282,7 +282,7 @@ CAResult_t CAEDRServerStop()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -413,7 +413,7 @@ CAResult_t CAEDRServerInitialize(ca_thread_pool_t handle)
 CAResult_t CAEDRServerStartAcceptThread()
 {
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -477,7 +477,7 @@ void CAEDRServerTerminate()
         return;
     }
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
index 7f36db3..c229b68 100644 (file)
@@ -72,14 +72,14 @@ CAResult_t CAEDRStartNetworkMonitor()
     {
         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth initialization failed!, error num [%x]",
                   ret);
-        return;
+        return CA_STATUS_FAILED;
     }
 
     ret = bt_adapter_set_state_changed_cb(CAEDRAdapterStateChangeCallback, NULL);
     if(BT_ERROR_NONE != ret)
     {
        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "bt_adapter_set_state_changed_cb failed");
-       return;
+       return CA_STATUS_FAILED;
     }
 
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
index 7f0ffd2..62b4fdc 100644 (file)
@@ -41,6 +41,8 @@
 
 #define MICROSECS_PER_SEC 1000000
 #define WAIT_TIME_WRITE_CHARACTERISTIC 10 * MICROSECS_PER_SEC
+#define WAIT_TIME_SCAN_INTERVAL_DEFAULT 10
+#define WAIT_TIME_SCANNED_CHECKING 30
 
 #define GATT_CONNECTION_PRIORITY_BALANCED   0
 #define GATT_FAILURE                        257
@@ -68,7 +70,6 @@ static jobjectArray g_uuidList = NULL;
 
 // it will be prevent to start send logic when adapter has stopped.
 static bool g_isStartedLEClient = false;
-static bool g_isStartedScan = false;
 
 static jbyteArray g_sendBuffer = NULL;
 static uint32_t g_targetCnt = 0;
@@ -94,9 +95,17 @@ static ca_mutex g_deviceStateListMutex = NULL;
 static ca_mutex g_deviceScanRetryDelayMutex = NULL;
 static ca_cond g_deviceScanRetryDelayCond = NULL;
 
-static ca_mutex g_scanMutex = NULL;
+static ca_mutex g_threadScanIntervalMutex = NULL;
+static ca_cond g_threadScanIntervalCond = NULL;
+
 static ca_mutex g_threadSendStateMutex = NULL;
 
+static int32_t g_scanIntervalTime = WAIT_TIME_SCAN_INTERVAL_DEFAULT;
+static int32_t g_scanIntervalTimePrev = WAIT_TIME_SCAN_INTERVAL_DEFAULT;
+static int32_t g_intervalCount = 0;
+static bool g_isWorkingScanThread = false;
+static CALEScanState_t g_scanningStep = BLE_SCAN_DISABLE;
+
 static CABLEDataReceivedCallback g_CABLEClientDataReceivedCallback = NULL;
 
 /**
@@ -125,6 +134,143 @@ static bool CALECheckConnectionStateValue(jint state)
     return false;
 }
 
+void CALEClientSetScanInterval(int32_t intervalTime, int32_t workingCount)
+{
+    OIC_LOG_V(DEBUG, TAG, "CALEClientSetScanInterval : %d -> %d",
+              g_scanIntervalTime, intervalTime);
+
+    // previous time should be stored.
+    if (0 < workingCount)
+    {
+        g_scanIntervalTimePrev = g_scanIntervalTime;
+    }
+    g_scanIntervalTime = intervalTime;
+    g_intervalCount = workingCount;
+}
+
+void CALERestartScanWithInterval(int32_t intervalTime, int32_t workingCount)
+{
+    // restart scan with interval
+    CALEClientSetScanInterval(intervalTime, workingCount);
+    ca_cond_signal(g_threadScanIntervalCond);
+}
+
+static void CALEScanThread(void* object)
+{
+    (void)object;
+
+    bool isAttached = false;
+    JNIEnv* env = NULL;
+    jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+    if (JNI_OK != res)
+    {
+        OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+        res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+        if (JNI_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+            return;
+        }
+        isAttached = true;
+    }
+
+    ca_mutex_lock(g_threadScanIntervalMutex);
+    while(g_isWorkingScanThread)
+    {
+        OIC_LOG(DEBUG, TAG, "scan waiting time out");
+        if (BLE_SCAN_ENABLE == g_scanningStep)
+        {
+            //stop scan
+            CAResult_t ret = CALEClientStopScan();
+            if (CA_STATUS_OK != ret)
+            {
+                OIC_LOG(INFO, TAG, "CALEClientStopScan has failed");
+            }
+        }
+        else
+        {
+            //start scan
+            CAResult_t ret = CALEClientStartScan();
+            if (CA_STATUS_OK != ret)
+            {
+                OIC_LOG(INFO, TAG, "CALEClientStartScan has failed");
+            }
+        }
+
+        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,
+                                                g_threadScanIntervalMutex,
+                                                g_scanIntervalTime * MICROSECS_PER_SEC))
+        {
+            // called signal scan thread will be terminated
+            OIC_LOG(DEBUG, TAG, "signal scanInterval waiting");
+            g_scanningStep = BLE_SCAN_DISABLE;
+        }
+        else
+        {
+           if (BLE_SCAN_ENABLE == g_scanningStep)
+           {
+               if (g_intervalCount > 0)
+               {
+                   if (g_intervalCount == 1)
+                   {
+                       OIC_LOG(DEBUG, TAG, "reset default time");
+                       CALEClientSetScanInterval(g_scanIntervalTimePrev, 0);
+                   }
+                   g_intervalCount--;
+                   OIC_LOG_V(DEBUG, TAG, "interval count : %d", g_intervalCount);
+               }
+               g_scanningStep = BLE_SCAN_DISABLE;
+           }
+           else
+           {
+               g_scanningStep = BLE_SCAN_ENABLE;
+           }
+        }
+    }
+    ca_mutex_unlock(g_threadScanIntervalMutex);
+
+    if (isAttached)
+    {
+        (*g_jvm)->DetachCurrentThread(g_jvm);
+    }
+}
+
+CAResult_t CALEClientStartScanWithInterval()
+{
+    OIC_LOG(DEBUG, TAG, "IN - CALEClientStartScanWithInterval");
+
+    if (g_isWorkingScanThread)
+    {
+        OIC_LOG(DEBUG, TAG, "scan interval logic already running");
+        return CA_STATUS_OK;
+    }
+
+    // initialize scan flags
+    g_scanningStep = BLE_SCAN_DISABLE;
+    g_isWorkingScanThread = true;
+    g_intervalCount = 0;
+    g_scanIntervalTime = g_scanIntervalTimePrev;
+
+    if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle,
+                                                CALEScanThread, NULL))
+    {
+        OIC_LOG(ERROR, TAG, "Failed to create read thread!");
+        g_isWorkingScanThread = false;
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, TAG, "OUT - CALEClientStartScanWithInterval");
+    return CA_STATUS_OK;
+}
+
+void CALEClientStopScanWithInterval()
+{
+    g_isWorkingScanThread = false;
+    ca_cond_signal(g_threadScanIntervalCond);
+}
+
 //getting jvm
 void CALEClientJniInit()
 {
@@ -155,7 +301,7 @@ CAResult_t CALECreateJniInterfaceObject()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -236,7 +382,7 @@ CAResult_t CALEClientInitialize()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -284,6 +430,7 @@ CAResult_t CALEClientInitialize()
     g_threadCond = ca_cond_new();
     g_threadWriteCharacteristicCond = ca_cond_new();
     g_deviceScanRetryDelayCond = ca_cond_new();
+    g_threadScanIntervalCond =  ca_cond_new();
 
     CALEClientCreateDeviceList();
     CALEClientJNISetContext();
@@ -334,7 +481,7 @@ void CALEClientTerminate()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -391,7 +538,6 @@ void CALEClientTerminate()
         OIC_LOG(ERROR, TAG, "CALEClientRemoveAllGattObjs has failed");
     }
 
-    CALEClientSetScanFlag(false);
     CALEClientSetSendFinishFlag(true);
 
     CALEClientTerminateGattMutexVariables();
@@ -401,14 +547,19 @@ void CALEClientTerminate()
     ca_cond_free(g_threadCond);
     ca_cond_free(g_threadWriteCharacteristicCond);
     ca_cond_free(g_deviceScanRetryDelayCond);
+    ca_cond_free(g_threadScanIntervalCond);
 
     g_deviceDescCond = NULL;
     g_threadCond = NULL;
     g_threadWriteCharacteristicCond = NULL;
     g_deviceScanRetryDelayCond = NULL;
+    g_threadScanIntervalCond = NULL;
 
     g_isSignalSetFlag = false;
 
+    // stop scanning
+    CALEClientStopScanWithInterval();
+
     if (isAttached)
     {
         (*g_jvm)->DetachCurrentThread(g_jvm);
@@ -426,7 +577,7 @@ CAResult_t CALEClientDestroyJniInterface()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -526,7 +677,7 @@ CAResult_t CALEClientSendMulticastMessage(const uint8_t* data,
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -609,6 +760,9 @@ CAResult_t CALEClientIsThereScannedDevices(JNIEnv *env, const char* address)
         static uint64_t const TIMEOUT =
             2 * MICROSECS_PER_SEC;  // Microseconds
 
+        // set scan interval and start scan
+        CALERestartScanWithInterval(WAIT_TIME_SCANNED_CHECKING, 1);
+
         bool devicesDiscovered = false;
         for (size_t i = 0; i < RETRIES; ++i)
         {
@@ -659,6 +813,9 @@ CAResult_t CALEClientIsThereScannedDevices(JNIEnv *env, const char* address)
             }
         }
 
+        // reset scan interval time after checking scanned devices
+        CALERestartScanWithInterval(g_scanIntervalTimePrev, 0);
+
         // time out for scanning devices
         if (!devicesDiscovered)
         {
@@ -671,7 +828,7 @@ CAResult_t CALEClientIsThereScannedDevices(JNIEnv *env, const char* address)
 
 
 CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t* data,
-                                      const uint32_t dataLen)
+                                            const uint32_t dataLen)
 {
     OIC_LOG_V(DEBUG, TAG, "CALEClientSendUnicastMessageImpl, address: %s, data: %p", address,
               data);
@@ -685,7 +842,7 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t*
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -743,13 +900,8 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t*
                 (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
                 (*env)->DeleteLocalRef(env, jni_setAddress);
 
-                // connect to gatt server
-                ret = CALEClientStopScan();
-                if (CA_STATUS_OK != ret)
-                {
-                    OIC_LOG(ERROR, TAG, "CALEClientStopScan has failed");
-                    goto error_exit;
-                }
+                // stop scan while sending
+                CALEClientStopScanWithInterval();
 
                 if (g_sendBuffer)
                 {
@@ -797,10 +949,10 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t*
     }
 
     // start LE Scan again
-    ret = CALEClientStartScan();
+    ret = CALEClientStartScanWithInterval();
     if (CA_STATUS_OK != ret)
     {
-        OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+        OIC_LOG(ERROR, TAG, "CALEClientStartScanWithInterval has failed");
         ca_mutex_unlock(g_threadSendMutex);
         return ret;
     }
@@ -818,11 +970,12 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t*
     }
 
     // reset send state
-    ret = CALEClientUpdateDeviceState(address, CA_LE_SEND_STATE,
-                                      STATE_SEND_NONE);
-    if (CA_STATUS_OK != ret)
+    CAResult_t resetRet = CALEClientUpdateDeviceState(address, CA_LE_SEND_STATE,
+                                                      STATE_SEND_NONE);
+    if (CA_STATUS_OK != resetRet)
     {
-        OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
+        OIC_LOG_V(ERROR, TAG, "CALEClientUpdateDeviceState has failed (%d)", resetRet);
+        ret = CA_SEND_FAILED;
     }
 
     return ret;
@@ -831,10 +984,10 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t*
 error_exit:
 
     // start LE Scan again
-    ret = CALEClientStartScan();
+    ret = CALEClientStartScanWithInterval();
     if (CA_STATUS_OK != ret)
     {
-        OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+        OIC_LOG(ERROR, TAG, "CALEClientStartScanWithInterval has failed");
         ca_mutex_unlock(g_threadSendMutex);
         if (isAttached)
         {
@@ -883,14 +1036,9 @@ CAResult_t CALEClientSendMulticastMessageImpl(JNIEnv *env, const uint8_t* data,
         goto error_exit;
     }
 
-    // connect to gatt server
-    res = CALEClientStopScan();
-    if (CA_STATUS_OK != res)
-    {
-        OIC_LOG(ERROR, TAG, "CALEClientStopScan has failed");
-        ca_mutex_unlock(g_threadSendMutex);
-        return res;
-    }
+    // stop scan while sending
+    CALEClientStopScanWithInterval();
+
     uint32_t length = u_arraylist_length(g_deviceList);
     g_targetCnt = length;
 
@@ -927,10 +1075,10 @@ CAResult_t CALEClientSendMulticastMessageImpl(JNIEnv *env, const uint8_t* data,
     ca_mutex_unlock(g_threadMutex);
 
     // start LE Scan again
-    res = CALEClientStartScan();
+    res = CALEClientStartScanWithInterval();
     if (CA_STATUS_OK != res)
     {
-        OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+        OIC_LOG(ERROR, TAG, "CALEClientStartScanWithInterval has failed");
         ca_mutex_unlock(g_threadSendMutex);
         return res;
     }
@@ -940,10 +1088,10 @@ CAResult_t CALEClientSendMulticastMessageImpl(JNIEnv *env, const uint8_t* data,
     return CA_STATUS_OK;
 
 error_exit:
-    res = CALEClientStartScan();
+    res = CALEClientStartScanWithInterval();
     if (CA_STATUS_OK != res)
     {
-        OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+        OIC_LOG(ERROR, TAG, "CALEClientStartScanWithInterval has failed");
         ca_mutex_unlock(g_threadSendMutex);
         return res;
     }
@@ -1150,14 +1298,8 @@ CAResult_t CALEClientStartScan()
         return CA_STATUS_FAILED;
     }
 
-    if (g_isStartedScan)
-    {
-        OIC_LOG(INFO, TAG, "scanning is already started");
-        return CA_STATUS_OK;
-    }
-
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -1230,6 +1372,7 @@ CAResult_t CALEClientStartScanImpl(JNIEnv *env, jobject callback)
     if (!jni_mid_getDefaultAdapter)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
         return CA_STATUS_FAILED;
     }
 
@@ -1240,6 +1383,7 @@ CAResult_t CALEClientStartScanImpl(JNIEnv *env, jobject callback)
     if (!jni_mid_startLeScan)
     {
         OIC_LOG(ERROR, TAG, "startLeScan: jni_mid_startLeScan is null");
+        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
         return CA_STATUS_FAILED;
     }
 
@@ -1249,6 +1393,7 @@ CAResult_t CALEClientStartScanImpl(JNIEnv *env, jobject callback)
     if (!jni_obj_BTAdapter)
     {
         OIC_LOG(ERROR, TAG, "getState From BTAdapter: jni_obj_BTAdapter is null");
+        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
         return CA_STATUS_FAILED;
     }
 
@@ -1263,9 +1408,10 @@ CAResult_t CALEClientStartScanImpl(JNIEnv *env, jobject callback)
     else
     {
         OIC_LOG(DEBUG, TAG, "LeScan has started");
-        CALEClientSetScanFlag(true);
     }
 
+    (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
+    (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
     return CA_STATUS_OK;
 }
 
@@ -1295,6 +1441,7 @@ CAResult_t CALEClientStartScanWithUUIDImpl(JNIEnv *env, jobjectArray uuids, jobj
     if (!jni_mid_getDefaultAdapter)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
         return CA_STATUS_FAILED;
     }
 
@@ -1305,6 +1452,7 @@ CAResult_t CALEClientStartScanWithUUIDImpl(JNIEnv *env, jobjectArray uuids, jobj
     if (!jni_mid_startLeScan)
     {
         OIC_LOG(ERROR, TAG, "startLeScan: jni_mid_startLeScan is null");
+        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
         return CA_STATUS_FAILED;
     }
 
@@ -1314,6 +1462,7 @@ CAResult_t CALEClientStartScanWithUUIDImpl(JNIEnv *env, jobjectArray uuids, jobj
     if (!jni_obj_BTAdapter)
     {
         OIC_LOG(ERROR, TAG, "getState From BTAdapter: jni_obj_BTAdapter is null");
+        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
         return CA_STATUS_FAILED;
     }
 
@@ -1328,9 +1477,10 @@ CAResult_t CALEClientStartScanWithUUIDImpl(JNIEnv *env, jobjectArray uuids, jobj
     else
     {
         OIC_LOG(DEBUG, TAG, "LeScan has started");
-        CALEClientSetScanFlag(true);
     }
 
+    (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
+    (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
     return CA_STATUS_OK;
 }
 
@@ -1376,14 +1526,8 @@ CAResult_t CALEClientStopScan()
         return CA_STATUS_FAILED;
     }
 
-    if (!g_isStartedScan)
-    {
-        OIC_LOG(INFO, TAG, "scanning is already stopped");
-        return CA_STATUS_OK;
-    }
-
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -1409,10 +1553,6 @@ CAResult_t CALEClientStopScan()
             OIC_LOG(ERROR, TAG, "CALEClientStopScanImpl has failed");
         }
     }
-    else
-    {
-        CALEClientSetScanFlag(false);
-    }
 
     if (isAttached)
     {
@@ -1422,13 +1562,6 @@ CAResult_t CALEClientStopScan()
     return ret;
 }
 
-void CALEClientSetScanFlag(bool flag)
-{
-    ca_mutex_lock(g_scanMutex);
-    g_isStartedScan = flag;
-    ca_mutex_unlock(g_scanMutex);
-}
-
 CAResult_t CALEClientStopScanImpl(JNIEnv *env, jobject callback)
 {
     OIC_LOG(DEBUG, TAG, "CALEClientStopScanImpl");
@@ -1456,6 +1589,7 @@ CAResult_t CALEClientStopScanImpl(JNIEnv *env, jobject callback)
     if (!jni_mid_getDefaultAdapter)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
         return CA_STATUS_FAILED;
     }
 
@@ -1466,6 +1600,7 @@ CAResult_t CALEClientStopScanImpl(JNIEnv *env, jobject callback)
     if (!jni_mid_stopLeScan)
     {
         OIC_LOG(ERROR, TAG, "stopLeScan: jni_mid_stopLeScan is null");
+        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
         return CA_STATUS_FAILED;
     }
 
@@ -1475,6 +1610,7 @@ CAResult_t CALEClientStopScanImpl(JNIEnv *env, jobject callback)
     if (!jni_obj_BTAdapter)
     {
         OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
         return CA_STATUS_FAILED;
     }
 
@@ -1484,11 +1620,15 @@ CAResult_t CALEClientStopScanImpl(JNIEnv *env, jobject callback)
     if ((*env)->ExceptionCheck(env))
     {
         OIC_LOG(ERROR, TAG, "stopLeScan has failed");
+        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
+        (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
         (*env)->ExceptionDescribe(env);
         (*env)->ExceptionClear(env);
         return CA_STATUS_FAILED;
     }
 
+    (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
+    (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
     return CA_STATUS_OK;
 }
 
@@ -1985,7 +2125,7 @@ static void CALEWriteCharacteristicThread(void* object)
     VERIFY_NON_NULL_VOID(object, TAG, "object is null");
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -2446,7 +2586,7 @@ CAResult_t CALEClientCreateUUIDList()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -2637,12 +2777,7 @@ CAResult_t CALEClientAddScanDeviceToList(JNIEnv *env, jobject device)
     if (!g_deviceList)
     {
         OIC_LOG(ERROR, TAG, "gdevice_list is null");
-
-        CALEClientSetScanFlag(false);
-        if (CA_STATUS_OK != CALEClientStopScan())
-        {
-            OIC_LOG(ERROR, TAG, "CALEClientStopScan has failed");
-        }
+        CALEClientStopScanWithInterval();
 
         ca_mutex_unlock(g_deviceListMutex);
         return CA_STATUS_FAILED;
@@ -3742,16 +3877,6 @@ CAResult_t CALEClientInitGattMutexVaraibles()
         }
     }
 
-    if (NULL == g_scanMutex)
-    {
-        g_scanMutex = ca_mutex_new();
-        if (NULL == g_scanMutex)
-        {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-
     if (NULL == g_threadWriteCharacteristicMutex)
     {
         g_threadWriteCharacteristicMutex = ca_mutex_new();
@@ -3782,6 +3907,16 @@ CAResult_t CALEClientInitGattMutexVaraibles()
         }
     }
 
+    if (NULL == g_threadScanIntervalMutex)
+    {
+        g_threadScanIntervalMutex = ca_mutex_new();
+        if (NULL == g_threadScanIntervalMutex)
+        {
+            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            return CA_STATUS_FAILED;
+        }
+    }
+
     return CA_STATUS_OK;
 }
 
@@ -3805,9 +3940,6 @@ void CALEClientTerminateGattMutexVariables()
     ca_mutex_free(g_SendFinishMutex);
     g_SendFinishMutex = NULL;
 
-    ca_mutex_free(g_scanMutex);
-    g_scanMutex = NULL;
-
     ca_mutex_free(g_threadWriteCharacteristicMutex);
     g_threadWriteCharacteristicMutex = NULL;
 
@@ -3816,6 +3948,9 @@ void CALEClientTerminateGattMutexVariables()
 
     ca_mutex_free(g_threadSendStateMutex);
     g_threadSendStateMutex = NULL;
+
+    ca_mutex_free(g_threadScanIntervalMutex);
+    g_threadScanIntervalMutex = NULL;
 }
 
 void CALEClientSetSendFinishFlag(bool flag)
@@ -3849,10 +3984,10 @@ CAResult_t CAStartLEGattClient()
         g_threadWriteCharacteristicCond = ca_cond_new();
     }
 
-    CAResult_t ret = CALEClientStartScan();
+    CAResult_t ret = CALEClientStartScanWithInterval();
     if (CA_STATUS_OK != ret)
     {
-        OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+        OIC_LOG(ERROR, TAG, "CALEClientStartScanWithInterval has failed");
         return ret;
     }
 
@@ -3871,7 +4006,7 @@ void CAStopLEGattClient()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -3892,11 +4027,7 @@ void CAStopLEGattClient()
         OIC_LOG(ERROR, TAG, "CALEClientDisconnectAll has failed");
     }
 
-    ret = CALEClientStopScan();
-    if(CA_STATUS_OK != ret)
-    {
-        OIC_LOG(ERROR, TAG, "CALEClientStopScan has failed");
-    }
+    CALEClientStopScanWithInterval();
 
     ca_mutex_lock(g_threadMutex);
     OIC_LOG(DEBUG, TAG, "signal - connection cond");
@@ -3914,15 +4045,22 @@ void CAStopLEGattClient()
     ca_cond_signal(g_deviceScanRetryDelayCond);
     ca_mutex_unlock(g_deviceScanRetryDelayMutex);
 
+    ca_mutex_lock(g_threadScanIntervalMutex);
+    OIC_LOG(DEBUG, TAG, "signal - delay cond");
+    ca_cond_signal(g_threadScanIntervalCond);
+    ca_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);
 
     g_deviceDescCond = NULL;
     g_threadCond = NULL;
     g_threadWriteCharacteristicCond = NULL;
     g_deviceScanRetryDelayCond = NULL;
+    g_threadScanIntervalCond = NULL;
 
     if (isAttached)
     {
@@ -4028,39 +4166,6 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeScanCallback(JNIEnv *env, jobject o
     }
 }
 
-static jstring CALEClientGetAddressFromGatt(JNIEnv *env, jobject gatt)
-{
-    OIC_LOG(DEBUG, TAG, "IN - CAManagerGetAddressFromGatt");
-
-    VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
-    VERIFY_NON_NULL_RET(gatt, TAG, "gatt is null", NULL);
-
-    jmethodID jni_mid_getDevice = CAGetJNIMethodID(env, CLASSPATH_BT_GATT,
-                                                   "getDevice", METHODID_BT_DEVICE);
-    if (!jni_mid_getDevice)
-    {
-        OIC_LOG(ERROR, TAG, "jni_mid_getDevice is null");
-        return NULL;
-    }
-
-    jobject jni_obj_device = (*env)->CallObjectMethod(env, gatt, jni_mid_getDevice);
-    if (!jni_obj_device)
-    {
-        OIC_LOG(ERROR, TAG, "jni_obj_device is null");
-        return NULL;
-    }
-
-    jstring jni_address = CALEGetAddressFromBTDevice(env, jni_obj_device);
-    if (!jni_address)
-    {
-        OIC_LOG(ERROR, TAG, "jni_address is null");
-        return NULL;
-    }
-
-    OIC_LOG(DEBUG, TAG, "OUT - CAManagerGetAddressFromGatt");
-    return jni_address;
-}
-
 /*
  * Class:     org_iotivity_ca_jar_caleinterface
  * Method:    CALeGattConnectionStateChangeCallback
@@ -4096,13 +4201,14 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattConnectionStateChangeCallback(J
     }
     OIC_LOG_V(DEBUG, TAG, "CALeGattConnectionStateChangeCallback - address [%s]", address);
 
-    CAResult_t res;
     if (state_connected == newstate)
     {
         OIC_LOG(DEBUG, TAG, "LE is connected");
         if (GATT_SUCCESS == status)
         {
-            res = CALEClientUpdateDeviceState(address, CA_LE_CONNECTION_STATE, STATE_CONNECTED);
+            CAResult_t res = CALEClientUpdateDeviceState(address,
+                                                         CA_LE_CONNECTION_STATE,
+                                                         STATE_CONNECTED);
             (*env)->ReleaseStringUTFChars(env, jni_address, address);
             if (CA_STATUS_OK != res)
             {
@@ -4134,7 +4240,9 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattConnectionStateChangeCallback(J
     {
         OIC_LOG(DEBUG, TAG, "LE is disconnected");
 
-        res = CALEClientUpdateDeviceState(address, CA_LE_CONNECTION_STATE, STATE_DISCONNECTED);
+        CAResult_t res = CALEClientUpdateDeviceState(address,
+                                                     CA_LE_CONNECTION_STATE,
+                                                     STATE_DISCONNECTED);
         (*env)->ReleaseStringUTFChars(env, jni_address, address);
         if (CA_STATUS_OK != res)
         {
@@ -4148,51 +4256,20 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattConnectionStateChangeCallback(J
             OIC_LOG(ERROR, TAG, "CALEClientGattClose has failed");
         }
 
-        if (GATT_ERROR == status)
+        if (CALECheckConnectionStateValue(status))
         {
-            // when we get GATT ERROR(0x85), gatt connection can be called again.
-            OIC_LOG(INFO, TAG, "retry gatt connect");
-
-            jstring leAddress = CALEClientGetAddressFromGatt(env, gatt);
-            if (!leAddress)
-            {
-                OIC_LOG(ERROR, TAG, "CALEClientGetAddressFromGatt has failed");
-                goto error_exit;
-            }
-
-            jobject btObject = CALEGetRemoteDevice(env, leAddress);
-            if (!btObject)
-            {
-                OIC_LOG(ERROR, TAG, "CALEGetRemoteDevice has failed");
-                goto error_exit;
-            }
-
-            jobject newGatt = CALEClientConnect(env, btObject, JNI_TRUE);
-            if (!newGatt)
-            {
-                OIC_LOG(ERROR, TAG, "CALEClientConnect has failed");
-                goto error_exit;
-            }
-
-            return;
+            // this state is unexpected reason to disconnect
+            // if the reason is suitable, connection logic of the device will be destroyed.
+            OIC_LOG(INFO, TAG, "connection logic destroy");
+            goto error_exit;
         }
         else
         {
-            if (CALECheckConnectionStateValue(status))
-            {
-                // this state is unexpected reason to disconnect
-                // if the reason is suitable, connection logic of the device will be destroyed.
-                OIC_LOG(INFO, TAG, "connection logic destroy");
-                goto error_exit;
-            }
-            else
-            {
-                // other reason except for gatt_success is expected to running
-                // background connection in BT platform.
-                OIC_LOG(INFO, TAG, "unknown status or manual disconnected state");
-                CALEClientUpdateSendCnt(env);
-                return;
-            }
+            // other reason except for gatt_success is expected to running
+            // background connection in BT platform.
+            OIC_LOG(INFO, TAG, "unknown status or manual disconnected state");
+            CALEClientUpdateSendCnt(env);
+            return;
         }
 
         if (g_sendBuffer)
index ee5ffc8..eb61cf4 100644 (file)
@@ -52,6 +52,15 @@ typedef struct le_state_info
 } CALEState_t;
 
 /**
+ * BLE Scanning State.
+ */
+typedef enum
+{
+    BLE_SCAN_ENABLE = 0, /**< BLE scan is working */
+    BLE_SCAN_DISABLE     /**< BLE scan is not working */
+} CALEScanState_t;
+
+/**
  * Callback to be notified on reception of any data from remote devices.
  * @param[in]  address                MAC address of remote device.
  * @param[in]  data                   Data received from remote device.
@@ -248,12 +257,6 @@ jobject CALEClientGetUUIDObject(JNIEnv *env, const char *uuid);
 CAResult_t CALEClientStopScan();
 
 /**
- * set ble scanning flag.
- * @param[in]   flag        scan flag.
- */
-void CALEClientSetScanFlag(bool flag);
-
-/**
  * stop scan (implement).
  * @param[in]   env                   JNI interface pointer.
  * @param[in]   callback              callback to receive device object by scanning.
@@ -603,6 +606,31 @@ jobject CALEClientGattConnect(JNIEnv *env, jobject bluetoothDevice, jboolean aut
  */
 CAResult_t CALEClientDirectConnect(JNIEnv *env, jobject bluetoothDevice, jboolean autoconnect);
 
+/**
+ * set new interval time and working count.
+ * @param[in]  intervalTime             interval time(Seconds).
+ * @param[in]  workingCount             working count for selected interval time.
+ */
+void CALEClientSetScanInterval(int32_t intervalTime, int32_t workingCount);
+
+/**
+ * restart scanning with new interval time and working count.
+ * @param[in]  intervalTime             interval time(Seconds).
+ * @param[in]  workingCount             working count for selected interval time.
+ */
+void CALERestartScanWithInterval(int32_t intervalTime, int32_t workingCount);
+
+/**
+ * start LE scanning logic with interval time and working count.
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CALEClientStartScanWithInterval();
+
+/**
+ * stop LE scanning logic with interval time and cycle.
+ */
+void CALEClientStopScanWithInterval();
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
index 04f21e8..4a65ed2 100644 (file)
@@ -158,7 +158,7 @@ CAResult_t CAGetLEAdapterState()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -343,8 +343,6 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeStateChangedCallback(JNIEnv *env, j
             OIC_LOG(ERROR, TAG, "CALEServerRemoveAllDevices has failed");
         }
 
-        CALEClientSetScanFlag(false);
-
         CANetworkStatus_t newStatus = CA_INTERFACE_DOWN;
         g_bleDeviceStateChangedCallback(newStatus);
     }
index c25157a..ec1555f 100644 (file)
@@ -103,7 +103,7 @@ CAResult_t CALEServerCreateJniInterfaceObject()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -407,7 +407,7 @@ CAResult_t CALEStartAdvertise()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -1453,7 +1453,7 @@ CAResult_t CALEServerInitialize()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -1530,7 +1530,7 @@ void CALEServerTerminate()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -1586,7 +1586,7 @@ CAResult_t CALEServerSendUnicastMessage(const char* address, const uint8_t* data
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -1627,7 +1627,7 @@ CAResult_t CALEServerSendMulticastMessage(const uint8_t* data, uint32_t dataLen)
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -1679,7 +1679,7 @@ CAResult_t CALEServerStartMulticastServer()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -1741,7 +1741,7 @@ CAResult_t CALEServerStopMulticastServer()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -2473,7 +2473,7 @@ CAResult_t CAStopLEGattServer()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
index b6ad36f..d863f9e 100644 (file)
@@ -295,6 +295,7 @@ jboolean CALEIsEnableBTAdapter(JNIEnv *env)
     if (!jni_mid_getDefaultAdapter)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
         return JNI_FALSE;
     }
 
@@ -303,6 +304,7 @@ jboolean CALEIsEnableBTAdapter(JNIEnv *env)
     if (!jni_obj_BTAdapter)
     {
         OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
         return JNI_FALSE;
     }
 
@@ -311,12 +313,16 @@ jboolean CALEIsEnableBTAdapter(JNIEnv *env)
     if (!jni_mid_isEnable)
     {
         OIC_LOG(ERROR, TAG, "jni_mid_isEnable is null");
+        (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
+        (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
         return JNI_FALSE;
     }
 
     jboolean jni_isEnable = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter, jni_mid_isEnable);
     OIC_LOG_V(DEBUG, TAG, "adapter state is %d", jni_isEnable);
 
+    (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
+    (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
     return jni_isEnable;
 }
 
index af2aa63..0fa538b 100644 (file)
@@ -72,7 +72,7 @@ static CABLEDataReceivedCallback g_leServerDataReceivedCallback = NULL;
 /**
  * Callback to notify any error in LE adapter.
  */
-static CABLEErrorHandleCallback g_serverErrorCallback;
+static CABLEErrorHandleCallback g_serverErrorCallback = NULL;
 
 /**
  * To keep the state of GATT server if started or not.
@@ -373,6 +373,7 @@ CAResult_t CAStopLEGattServer()
             // Kill g main loops and kill threads
             g_main_loop_quit(g_eventLoop);
         }
+        g_eventLoop = NULL;
     }
     else
     {
@@ -526,22 +527,17 @@ CAResult_t CAInitLEGattServer()
         return CA_STATUS_FAILED;
     }
 
-    bt_gatt_server_h server;
-
-    ret = bt_gatt_server_create(&server);
-    if (0 != ret)
-    {
-        OIC_LOG_V(ERROR, TAG, "bt_gatt_server_create failed with ret[%s]",
-                  CALEGetErrorMsg(ret));
-        return CA_STATUS_FAILED;
-    }
-
-    if (NULL != g_gattServer)
+    if (!g_gattServer)
     {
-        OICFree(g_gattServer);
-        g_gattServer = NULL;
+        OIC_LOG(DEBUG, TAG, "g_gattServer is NULL. create gatt server..");
+        ret = bt_gatt_server_create(&g_gattServer);
+        if (0 != ret)
+        {
+            OIC_LOG_V(ERROR, TAG, "bt_gatt_server_create failed with ret[%s]",
+                      CALEGetErrorMsg(ret));
+            return CA_STATUS_FAILED;
+        }
     }
-    g_gattServer = server;
 
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
@@ -566,6 +562,7 @@ CAResult_t CADeInitLEGattServer()
                   CALEGetErrorMsg(ret));
         return CA_STATUS_FAILED;
     }
+    g_gattServer = NULL;
 
     ret =  bt_gatt_server_deinitialize();
     if (0 != ret)
@@ -596,31 +593,22 @@ CAResult_t CAAddNewLEServiceInGattServer(const char *serviceUUID)
 
     OIC_LOG_V(DEBUG, TAG, "service uuid %s", serviceUUID);
 
-    bt_gatt_h service = NULL;
     bt_gatt_service_type_e type = BT_GATT_SERVICE_TYPE_PRIMARY;
 
-    int ret = bt_gatt_service_create(serviceUUID, type, &service);
+    ca_mutex_lock(g_leServiceMutex);
+    int ret = bt_gatt_service_create(serviceUUID, type, &g_gattSvcPath);
     if (0 != ret)
     {
+        ca_mutex_unlock(g_leServiceMutex);
         OIC_LOG_V(ERROR, TAG, "bt_gatt_service_create failed with ret [%s]",
-                  CALEGetErrorMsg(ret));
+                    CALEGetErrorMsg(ret));
         return CA_STATUS_FAILED;
     }
+    ca_mutex_unlock(g_leServiceMutex);
 
-    if (NULL != service)
+    if (g_gattSvcPath)
     {
-        OIC_LOG_V(DEBUG, TAG, "ServicePath obtained is %s", (char *)service);
-
-        ca_mutex_lock(g_leServiceMutex);
-
-        if (NULL != g_gattSvcPath)
-        {
-            OICFree(g_gattSvcPath);
-            g_gattSvcPath = NULL;
-        }
-        g_gattSvcPath = service;
-
-        ca_mutex_unlock(g_leServiceMutex);
+        OIC_LOG_V(DEBUG, TAG, "ServicePath obtained is %s", (char *)g_gattSvcPath);
     }
 
     OIC_LOG(DEBUG, TAG, "OUT");
@@ -707,7 +695,7 @@ CAResult_t CAAddNewCharacteristicsToGattServer(const bt_gatt_h svcPath, const ch
 
     int permissions = BT_GATT_PERMISSION_READ | BT_GATT_PERMISSION_WRITE;
     int properties;
-    if(read)
+    if (read)
     {
         properties = BT_GATT_PROPERTY_NOTIFY | BT_GATT_PROPERTY_READ;
     }
@@ -716,7 +704,7 @@ CAResult_t CAAddNewCharacteristicsToGattServer(const bt_gatt_h svcPath, const ch
         properties = BT_GATT_PROPERTY_WRITE | BT_GATT_PROPERTY_READ;
     }
 
-    bt_gatt_h charPath;
+    bt_gatt_h charPath = NULL;
 
     int ret = bt_gatt_characteristic_create(charUUID, permissions, properties, charValue,
                                             charValueLen, &charPath);
@@ -764,6 +752,7 @@ CAResult_t CAAddNewCharacteristicsToGattServer(const bt_gatt_h svcPath, const ch
                                         &descriptor);
         if (0 != ret)
         {
+            ca_mutex_unlock(g_leCharacteristicMutex);
             OIC_LOG_V(ERROR, TAG,
                       "bt_gatt_descriptor_create  failed with ret[%s]",
                       CALEGetErrorMsg(ret));
@@ -773,27 +762,17 @@ 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);
             OIC_LOG_V(ERROR, TAG,
                       "bt_gatt_characteristic_add_descriptor  failed with ret[%s]",
                       CALEGetErrorMsg(ret));
             return CA_STATUS_FAILED;
         }
 
-        if (NULL != g_gattReadCharPath)
-        {
-            OICFree(g_gattReadCharPath);
-            g_gattReadCharPath = NULL;
-        }
         g_gattReadCharPath = charPath;
-
     }
     else
     {
-        if (NULL != g_gattWriteCharPath)
-        {
-            OICFree(g_gattWriteCharPath);
-            g_gattWriteCharPath = NULL;
-        }
         g_gattWriteCharPath = charPath;
     }
 
index a78aa06..a6a9cf5 100644 (file)
@@ -346,6 +346,16 @@ CAResult_t CAReceiveBlockWiseData(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
             return CA_STATUS_FAILED;
         }
 
+        // If we didn't send the last block message and received EMPTY message,
+        // we have to remain the block data from list.
+        CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
+        if (data && (data->block1.m || data->block2.m))
+        {
+            OIC_LOG(DEBUG, TAG, "this is normal EMPTY message for blockwise-transfer.");
+            CADestroyBlockID(blockDataID);
+            return CA_STATUS_OK;
+        }
+
         CARemoveBlockDataFromList(blockDataID);
         CADestroyBlockID(blockDataID);
         return CA_NOT_SUPPORTED;
@@ -483,23 +493,20 @@ CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData
                 return CA_STATUS_FAILED;
             }
 
-            if (data->requestInfo)
-            {
-                data->requestInfo->info.messageId = pdu->hdr->coap_hdr_udp_t.id;
-            }
-
             if (data->responseInfo)
             {
+                data->responseInfo->info.type =
+                        (pdu->hdr->coap_hdr_udp_t.type == CA_MSG_CONFIRM) ?
+                                CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM;
                 data->responseInfo->info.messageId = pdu->hdr->coap_hdr_udp_t.id;
-            }
 
-            res = CAAddSendThreadQueue(data, blockID);
-            if (CA_STATUS_OK != res)
-            {
-                OIC_LOG(ERROR, TAG, "add has failed");
-                return res;
+                res = CAAddSendThreadQueue(data, blockID);
+                if (CA_STATUS_OK != res)
+                {
+                    OIC_LOG(ERROR, TAG, "add has failed");
+                    return res;
+                }
             }
-
             break;
 
         case CA_OPTION1_RESPONSE:
@@ -578,6 +585,21 @@ CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData
     return CA_STATUS_OK;
 }
 
+static CAResult_t CASendDirectEmptyResponse(const CAEndpoint_t *endpoint, uint16_t messageId)
+{
+    OIC_LOG(DEBUG, TAG, "Entering CASendDirectEmptyResponse");
+    CAResponseInfo_t respInfo = {
+        .result = CA_EMPTY
+    };
+    respInfo.info.type = CA_MSG_ACKNOWLEDGE;
+    respInfo.info.messageId = messageId;
+
+    CAResult_t caResult = CASendResponse(endpoint, &respInfo);
+
+    OIC_LOG(DEBUG, TAG, "Exit CASendDirectEmptyResponse");
+    return caResult;
+}
+
 CAResult_t CASendBlockMessage(const coap_pdu_t *pdu, CAMessageType_t msgType,
                               const CABlockDataID_t *blockID)
 {
@@ -619,9 +641,18 @@ CAResult_t CASendBlockMessage(const coap_pdu_t *pdu, CAMessageType_t msgType,
     }
     else
     {
-        OIC_LOG(DEBUG, TAG, "need new msgID");
+        // if the received response message type is CON, send empty message.
+        // and then, send next block request message with new messagId.
+        if (msgType == CA_MSG_CONFIRM)
+        {
+            CASendDirectEmptyResponse(data->remoteEndpoint,
+                                      data->requestInfo->info.messageId);
+            sentMsgType = CA_MSG_CONFIRM;
+        }
+
         if (data->requestInfo)
         {
+            OIC_LOG(DEBUG, TAG, "need new msgID");
             data->requestInfo->info.messageId = 0;
             data->requestInfo->info.type = sentMsgType;
         }
@@ -782,6 +813,44 @@ CAResult_t CAReceiveLastBlock(const CABlockDataID_t *blockID, const CAData_t *re
     return CA_STATUS_OK;
 }
 
+static CABlockData_t* CACheckTheExistOfBlockData(const CABlockDataID_t* blockDataID,
+                                                 coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
+                                                 uint8_t blockType)
+{
+    // Get BlockData data. If does not exist, create a new data
+    CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
+    if (!data)
+    {
+        OIC_LOG(DEBUG, TAG, "block data doesn't exist in list. create new one");
+
+        CAData_t *cadata = CACreateNewDataSet(pdu, endpoint);
+        if (!cadata)
+        {
+            OIC_LOG(ERROR, TAG, "data is null");
+            return NULL;
+        }
+
+        data = CACreateNewBlockData(cadata);
+        if (!data)
+        {
+            OIC_LOG(ERROR, TAG, "failed to create a new block data");
+            CADestroyDataSet(cadata);
+            return NULL;
+        }
+        CADestroyDataSet(cadata);
+    }
+
+    // update BLOCK OPTION type
+    CAResult_t res = CAUpdateBlockOptionType(blockDataID, blockType);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "update has failed");
+        return NULL;
+    }
+
+    return data;
+}
+
 // TODO make pdu const after libcoap is updated to support that.
 CAResult_t CASetNextBlockOption1(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                                  const CAData_t *receivedData, coap_block_t block,
@@ -806,39 +875,15 @@ CAResult_t CASetNextBlockOption1(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
         return CA_STATUS_FAILED;
     }
 
-    // Get BlockData data. If does not exist, create a new data
-    CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
+    CABlockData_t *data = CACheckTheExistOfBlockData(blockDataID, pdu, endpoint,
+                                                     COAP_OPTION_BLOCK1);
     if (!data)
     {
-        OIC_LOG(DEBUG, TAG, "block data doesn't exist in list. create new one");
-
-        CAData_t *cadata = CACreateNewDataSet(pdu, endpoint);
-        if (!cadata)
-        {
-            OIC_LOG(ERROR, TAG, "data is null");
-            CADestroyBlockID(blockDataID);
-            return CA_STATUS_FAILED;
-        }
-
-        data = CACreateNewBlockData(cadata);
-        if (!data)
-        {
-            OIC_LOG(ERROR, TAG, "failed to create a new block data");
-            CADestroyDataSet(cadata);
-            CADestroyBlockID(blockDataID);
-            return CA_STATUS_FAILED;
-        }
-        CADestroyDataSet(cadata);
-    }
-
-    // update BLOCK OPTION1 type
-    CAResult_t res = CAUpdateBlockOptionType(blockDataID, COAP_OPTION_BLOCK1);
-    if (CA_STATUS_OK != res)
-    {
-        OIC_LOG(ERROR, TAG, "update has failed");
+        OIC_LOG(ERROR, TAG, "Failed to create or get block data");
         goto exit;
     }
 
+    CAResult_t res = CA_STATUS_OK;
     uint8_t blockWiseStatus = CA_BLOCK_UNKNOWN;
     uint32_t code = pdu->hdr->coap_hdr_udp_t.code;
     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
@@ -886,15 +931,8 @@ CAResult_t CASetNextBlockOption1(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
         {
             OIC_LOG_V(DEBUG, TAG, "M bit is %d", block.m);
 
-            if (0 == block.m)
-            {
-                // Last block is received
-                blockWiseStatus = CA_OPTION1_REQUEST_LAST_BLOCK;
-            }
-            else
-            {
-                blockWiseStatus = CA_OPTION1_REQUEST_BLOCK;
-            }
+            blockWiseStatus = (0 == block.m) ?
+                    CA_OPTION1_REQUEST_LAST_BLOCK : CA_OPTION1_REQUEST_BLOCK;
         }
     }
     else
@@ -979,39 +1017,15 @@ CAResult_t CASetNextBlockOption2(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
         return CA_STATUS_FAILED;
     }
 
-    // Get BlockData data. If does not exist, create a new data
-    CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
+    CABlockData_t *data = CACheckTheExistOfBlockData(blockDataID, pdu, endpoint,
+                                                     COAP_OPTION_BLOCK2);
     if (!data)
     {
-        OIC_LOG(DEBUG, TAG, "block data doesn't exist in list. create new one");
-
-        CAData_t *cadata = CACreateNewDataSet(pdu, endpoint);
-        if (!cadata)
-        {
-            OIC_LOG(ERROR, TAG, "data is null");
-            CADestroyBlockID(blockDataID);
-            return CA_STATUS_FAILED;
-        }
-
-        data = CACreateNewBlockData(cadata);
-        if (!data)
-        {
-            OIC_LOG(ERROR, TAG, "failed to create a new block data");
-            CADestroyDataSet(cadata);
-            CADestroyBlockID(blockDataID);
-            return CA_STATUS_FAILED;
-        }
-        CADestroyDataSet(cadata);
-    }
-
-    // set Block Option Type
-    CAResult_t res = CAUpdateBlockOptionType(blockDataID, COAP_OPTION_BLOCK2);
-    if (CA_STATUS_OK != res)
-    {
-        OIC_LOG(ERROR, TAG, "update has failed");
+        OIC_LOG(ERROR, TAG, "Failed to create or get block data");
         goto exit;
     }
 
+    CAResult_t res = CA_STATUS_OK;
     uint8_t blockWiseStatus = CA_BLOCK_UNKNOWN;
     if (0 == block.num && CA_GET == pdu->hdr->coap_hdr_udp_t.code && 0 == block.m)
     {
@@ -2042,6 +2056,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.resourceUri = OICStrdup(resInfo->info.resourceUri);
 
         // after copying the resource uri, destroy response info.
@@ -2205,8 +2220,7 @@ CAResult_t CAHandleBlockErrorResponse(coap_block_t *block, uint16_t blockType,
     return CA_STATUS_OK;
 }
 
-CAResult_t CAUpdateBlockOptionType(const CABlockDataID_t *blockID,
-                                   uint8_t blockType)
+CAResult_t CAUpdateBlockOptionType(const CABlockDataID_t *blockID, uint8_t blockType)
 {
     OIC_LOG(DEBUG, TAG, "IN-UpdateBlockOptionType");
     VERIFY_NON_NULL(blockID, TAG, "blockID");
@@ -2333,93 +2347,35 @@ CAResult_t CACheckBlockDataValidation(const CAData_t *sendData, CABlockData_t **
     VERIFY_NON_NULL(sendData, TAG, "sendData");
     VERIFY_NON_NULL(blockData, TAG, "blockData");
 
-    CABlockDataID_t* blockDataID;
-    if(sendData->requestInfo)
-    {
-        blockDataID = CACreateBlockDatablockId(
-                            (CAToken_t)sendData->requestInfo->info.token,
-                            sendData->requestInfo->info.tokenLength,
-                            sendData->remoteEndpoint->port);
-    }
-    else if(sendData->responseInfo)
-    {
-        blockDataID = CACreateBlockDatablockId(
-                            (CAToken_t)sendData->responseInfo->info.token,
-                            sendData->responseInfo->info.tokenLength,
-                            sendData->remoteEndpoint->port);
-    }
-    else
+    if (sendData->responseInfo)
     {
-        OIC_LOG(ERROR, TAG, "sendData doesn't have requestInfo or responseInfo");
-        return CA_STATUS_FAILED;
-    }
-
-    if (NULL == blockDataID || blockDataID->idLength < 1)
-    {
-        OIC_LOG(ERROR, TAG, "blockId is null");
-        CADestroyBlockID(blockDataID);
-        return CA_STATUS_FAILED;
-    }
-
-    ca_mutex_lock(g_context.blockDataListMutex);
-
-    size_t len = u_arraylist_length(g_context.dataList);
-    for (size_t i = 0; i < len; i++)
-    {
-        CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
-        if (!currData)
+        CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
+                (CAToken_t)sendData->responseInfo->info.token,
+                sendData->responseInfo->info.tokenLength,
+                sendData->remoteEndpoint->port);
+        if (NULL == blockDataID || blockDataID->idLength < 1)
         {
-            continue;
+            OIC_LOG(ERROR, TAG, "blockId is null");
+            CADestroyBlockID(blockDataID);
+            return CA_STATUS_FAILED;
         }
 
-        if (sendData->requestInfo) // sendData is requestMessage
-        {
-            OIC_LOG(DEBUG, TAG, "Send request");
-            if (NULL != currData->blockDataId
-                    && NULL != currData->blockDataId->id
-                    && currData->blockDataId->idLength > 0
-                    && NULL != sendData->requestInfo->info.token)
-            {
-                if (CABlockidMatches(currData, blockDataID))
-                {
-                    OIC_LOG(ERROR, TAG, "already sent");
-                    continue;
-                }
-            }
-        }
-        else if (sendData->responseInfo) // sendData is responseMessage
+        CABlockData_t *storedData = CAGetBlockDataFromBlockDataList(blockDataID);
+        if (storedData)
         {
-            OIC_LOG(DEBUG, TAG, "Send response");
-            if (NULL != currData->blockDataId
-                    && NULL != currData->blockDataId->id
-                    && currData->blockDataId->idLength > 0
-                    && NULL != sendData->responseInfo->info.token)
+            OIC_LOG(DEBUG, TAG, "Send response about the received block request.");
+            if (storedData->sentData)
             {
-                if (CABlockidMatches(currData, blockDataID))
-                {
-                    // set sendData
-                    if (NULL != currData->sentData)
-                    {
-                        OIC_LOG(DEBUG, TAG, "init block number");
-                        CADestroyDataSet(currData->sentData);
-                    }
-                    currData->sentData = CACloneCAData(sendData);
-                    *blockData = currData;
-                    ca_mutex_unlock(g_context.blockDataListMutex);
-                    CADestroyBlockID(blockDataID);
-                    return CA_STATUS_OK;
-                }
+                OIC_LOG(DEBUG, TAG, "init block number");
+                CADestroyDataSet(storedData->sentData);
             }
+            storedData->sentData = CACloneCAData(sendData);
+            *blockData = storedData;
+            CADestroyBlockID(blockDataID);
+            return CA_STATUS_OK;
         }
-        else
-        {
-            OIC_LOG(ERROR, TAG, "no CAInfo data");
-            continue;
-        }
+        CADestroyBlockID(blockDataID);
     }
-    ca_mutex_unlock(g_context.blockDataListMutex);
-
-    CADestroyBlockID(blockDataID);
 
     return CA_STATUS_FAILED;
 }
index 82919b7..7355e2a 100644 (file)
@@ -100,7 +100,7 @@ CAResult_t CAStartListeningServer()
 {
     OIC_LOG(DEBUG, TAG, "CAStartListeningServer");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -112,7 +112,7 @@ CAResult_t CAStopListeningServer()
 {
     OIC_LOG(DEBUG, TAG, "CAStopListeningServer");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -124,7 +124,7 @@ CAResult_t CAStartDiscoveryServer()
 {
     OIC_LOG(DEBUG, TAG, "CAStartDiscoveryServer");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -137,7 +137,7 @@ void CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHand
 {
     OIC_LOG(DEBUG, TAG, "CARegisterHandler");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         OIC_LOG(DEBUG, TAG, "CA is not initialized");
         return;
@@ -151,7 +151,7 @@ CAResult_t CARegisterDTLSHandshakeCallback(CAErrorCallback dtlsHandshakeCallback
 {
     OIC_LOG(DEBUG, TAG, "CARegisterDTLSHandshakeCallback");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -165,7 +165,7 @@ CAResult_t CARegisterDTLSCredentialsHandler(CAGetDTLSPskCredentialsHandler GetDT
 {
     OIC_LOG(DEBUG, TAG, "CARegisterDTLSCredentialsHandler");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -180,7 +180,7 @@ CAResult_t CARegisterDTLSX509CredentialsHandler(CAGetDTLSX509CredentialsHandler
 {
     OIC_LOG(DEBUG, TAG, "CARegisterDTLSX509CredentialsHandler");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -193,7 +193,7 @@ CAResult_t CARegisterDTLSCrlHandler(CAGetDTLSCrlHandler GetDTLSCrlHandler)
 {
     OIC_LOG(DEBUG, TAG, "CARegisterDTLSCrlHandler");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -251,7 +251,7 @@ CAResult_t CAGetNetworkInformation(CAEndpoint_t **info, uint32_t *size)
 {
     OIC_LOG(DEBUG, TAG, "CAGetNetworkInformation");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -306,7 +306,7 @@ CAResult_t CASendRequest(const CAEndpoint_t *object, const CARequestInfo_t *requ
 {
     OIC_LOG(DEBUG, TAG, "CASendRequest");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -326,7 +326,7 @@ CAResult_t CASendResponse(const CAEndpoint_t *object, const CAResponseInfo_t *re
 {
     OIC_LOG(DEBUG, TAG, "CASendResponse");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -346,7 +346,7 @@ CAResult_t CASelectNetwork(CATransportAdapter_t interestedNetwork)
 {
     OIC_LOG_V(DEBUG, TAG, "Selected network : %d", interestedNetwork);
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -402,7 +402,7 @@ CAResult_t CAUnSelectNetwork(CATransportAdapter_t nonInterestedNetwork)
 {
     OIC_LOG_V(DEBUG, TAG, "unselected network : %d", nonInterestedNetwork);
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
index 7ae093c..5de93f1 100644 (file)
@@ -75,7 +75,7 @@ static int CAGetAdapterIndex(CATransportAdapter_t cType)
 
 static void CARegisterCallback(CAConnectivityHandler_t handler)
 {
-    if(handler.startAdapter == NULL ||
+    if (handler.startAdapter == NULL ||
         handler.startListenServer == NULL ||
         handler.stopListenServer == NULL ||
         handler.startDiscoveryServer == NULL ||
@@ -438,7 +438,7 @@ CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, u
     {
         void* ptrType = u_arraylist_get(list, i);
 
-        if(NULL == ptrType)
+        if (NULL == ptrType)
         {
             continue;
         }
@@ -451,9 +451,8 @@ CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, u
 
         int index = CAGetAdapterIndex(connType);
         if (0 > index)
-        if (-1 == index)
         {
-            OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+            OIC_LOG(ERROR, TAG, "unknown connectivity type!");
             continue;
         }
 
index a9d554e..d6c2c55 100644 (file)
@@ -140,9 +140,8 @@ static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
     }
 
     OIC_LOG_V(DEBUG, TAG, "address : %s", ep->addr);
-    CAResult_t result;
 
-    if(CA_RESPONSE_DATA == dataType)
+    if (CA_RESPONSE_DATA == dataType)
     {
         CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
         if (!resInfo)
@@ -153,7 +152,7 @@ static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
             return NULL;
         }
 
-        result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
+        CAResult_t result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
         if (CA_STATUS_OK != result)
         {
             OIC_LOG(ERROR, TAG, "CAGetResponseInfoFromPDU Failed");
@@ -182,7 +181,7 @@ static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
             return NULL;
         }
 
-        result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
+        CAResult_t result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
         if (CA_STATUS_OK != result)
         {
             OIC_LOG(ERROR, TAG, "CAGetRequestInfoFromPDU failed");
@@ -415,7 +414,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_transport_type transport = coap_udp;
     CAResult_t res = CA_SEND_FAILED;
     if (NULL != data->requestInfo)
     {
@@ -520,11 +519,12 @@ 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_transport_type transport = coap_udp;
 
     if (SEND_TYPE_UNICAST == type)
     {
         OIC_LOG(DEBUG,TAG,"Unicast message");
+
 #ifdef ROUTING_GATEWAY
         /*
          * When forwarding a packet, do not attempt retransmission as its the responsibility of
@@ -903,12 +903,12 @@ static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sen
         return NULL;
     }
 
-    if(CA_REQUEST_DATA == dataType)
+    if (CA_REQUEST_DATA == dataType)
     {
         // clone request info
         CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
 
-        if(!request)
+        if (!request)
         {
             OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
             goto exit;
@@ -917,7 +917,7 @@ static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sen
         cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
         cadata->requestInfo =  request;
     }
-    else if(CA_RESPONSE_DATA == dataType)
+    else if (CA_RESPONSE_DATA == dataType)
     {
         // clone response info
         CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
@@ -983,7 +983,7 @@ CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg
 
 #ifdef SINGLE_THREAD
     CAResult_t result = CAProcessSendData(data);
-    if(CA_STATUS_OK != result)
+    if (CA_STATUS_OK != result)
     {
         OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
         CADestroyData(data, sizeof(CAData_t));
@@ -997,7 +997,7 @@ CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg
     {
         // send block data
         CAResult_t res = CASendBlockWiseData(data);
-        if(CA_NOT_SUPPORTED == res)
+        if (CA_NOT_SUPPORTED == res)
         {
             OIC_LOG(DEBUG, TAG, "normal msg will be sent");
             CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
@@ -1251,7 +1251,7 @@ void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
 
 static void CALogPayloadInfo(CAInfo_t *info)
 {
-    if(info)
+    if (info)
     {
         if (info->options)
         {
index 7d84c1c..03eca3b 100644 (file)
@@ -45,7 +45,6 @@
 
 #define TAG "OIC_CA_PRTCL_MSG"
 
-#define CA_BUFSIZE (128)
 #define CA_PDU_MIN_SIZE (4)
 #define CA_ENCODE_BUFFER_SIZE (4)
 
@@ -313,7 +312,7 @@ coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
 #endif
     {
         OIC_LOG_V(DEBUG, TAG, "msgID is %d", info->messageId);
-        uint16_t message_id;
+        uint16_t message_id = 0;
         if (0 == info->messageId)
         {
             /* initialize message id */
@@ -447,7 +446,7 @@ CAResult_t CAParseUriPartial(const unsigned char *str, size_t length, int target
     }
     else if (str && length)
     {
-        unsigned char uriBuffer[CA_BUFSIZE] = { 0 };
+        unsigned char uriBuffer[CA_MAX_URI_LENGTH] = { 0 };
         unsigned char *pBuf = uriBuffer;
         size_t buflen = sizeof(uriBuffer);
         int res = (target == COAP_OPTION_URI_PATH) ? coap_split_path(str, length, pBuf, &buflen) :
@@ -662,7 +661,7 @@ int CAOrderOpts(void *a, void *b)
 uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
 {
     uint32_t count = 0;
-    coap_opt_t *option;
+    coap_opt_t *option = NULL;
 
     while ((option = coap_option_next(&opt_iter)))
     {
@@ -747,7 +746,7 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
         }
     }
 
-    coap_opt_t *option;
+    coap_opt_t *option = NULL;
     char optionResult[CA_MAX_URI_LENGTH] = {0};
     uint32_t idx = 0;
     uint32_t optionLength = 0;
@@ -962,17 +961,13 @@ CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo,
     VERIFY_NON_NULL(outInfo, TAG, "outInfo");
     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
 
-    coap_transport_type transport;
+    coap_transport_type transport = coap_udp;
 #ifdef WITH_TCP
     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
     {
         transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu_hdr)[0] >> 4);
     }
-    else
 #endif
-    {
-        transport = coap_udp;
-    }
 
     unsigned char* token = NULL;
     unsigned int token_length = 0;
@@ -1053,7 +1048,9 @@ uint32_t CAGetOptionData(uint16_t key, const uint8_t *data, uint32_t len,
         // should remain that way so a 0 byte of length 1 is inserted.
         len = 1;
         option[0]=0;
-    } else {
+    }
+    else
+    {
         memcpy(option, data, len);
         option[len] = '\0';
     }
index 9a6c56a..3e10065 100644 (file)
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
+#endif
 
 #include "caqueueingthread.h"
 #include "oic_malloc.h"
@@ -39,7 +43,6 @@ static void CAQueueingThreadBaseRoutine(void *threadValue)
     if (NULL == thread)
     {
         OIC_LOG(ERROR, TAG, "thread data passing error!!");
-
         return;
     }
 
@@ -124,28 +127,30 @@ CAResult_t CAQueueingThreadInitialize(CAQueueingThread_t *thread, ca_thread_pool
     thread->isStop = true;
     thread->threadTask = task;
     thread->destroy = destroy;
-    if(NULL == thread->dataQueue || NULL == thread->threadMutex || NULL == thread->threadCond)
+    if (NULL == thread->dataQueue || NULL == thread->threadMutex || NULL == thread->threadCond)
+    {
         goto ERROR_MEM_FAILURE;
+    }
 
     return CA_STATUS_OK;
-    ERROR_MEM_FAILURE:
-    if(thread->dataQueue)
+
+ERROR_MEM_FAILURE:
+    if (thread->dataQueue)
     {
         u_queue_delete(thread->dataQueue);
         thread->dataQueue = NULL;
     }
-    if(thread->threadMutex)
+    if (thread->threadMutex)
     {
         ca_mutex_free(thread->threadMutex);
         thread->threadMutex = NULL;
     }
-    if(thread->threadCond)
+    if (thread->threadCond)
     {
         ca_cond_free(thread->threadCond);
         thread->threadCond = NULL;
     }
     return CA_MEMORY_ALLOC_FAILED;
-
 }
 
 CAResult_t CAQueueingThreadStart(CAQueueingThread_t *thread)
@@ -247,7 +252,7 @@ CAResult_t CAQueueingThreadDestroy(CAQueueingThread_t *thread)
         u_queue_message_t *message = u_queue_get_element(thread->dataQueue);
 
         // free
-        if(NULL != message)
+        if (NULL != message)
         {
             if (NULL != thread->destroy)
             {
index 5fa8df9..52482b3 100644 (file)
 #include <string.h>
 
 #ifndef SINGLE_THREAD
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#include <time.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
+#if HAVE_SYS_TIMEB_H
+#include <sys/timeb.h>
+#endif
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif
+#endif
 
 #if defined(__ANDROID__)
 #include <linux/time.h>
@@ -59,6 +68,7 @@
 #include "caremotehandler.h"
 #include "caprotocolmessage.h"
 #include "oic_malloc.h"
+#include "ocrandom.h"
 #include "logger.h"
 
 #define TAG "OIC_CA_RETRANS"
@@ -77,6 +87,7 @@ typedef struct
 } CARetransmissionData_t;
 
 static const uint64_t USECS_PER_SEC = 1000000;
+static const uint64_t MSECS_PER_SEC = 1000;
 
 /**
  * @brief   getCurrent monotonic time
@@ -94,8 +105,13 @@ uint64_t getCurrentTimeInMicroSeconds();
  */
 static uint64_t CAGetTimeoutValue()
 {
-    return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * (random() & 0xFF)) >> 8)) *
+#ifdef HAVE_SRANDOM
+    return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * OCGetRandomByte()) >> 8)) *
+            (uint64_t) 1000;
+#else
+    return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * OCGetRandomByte()) >> 8)) *
             (uint64_t) 1000;
+#endif
 }
 
 CAResult_t CARetransmissionStart(CARetransmission_t *context)
@@ -646,6 +662,10 @@ uint64_t getCurrentTimeInMicroSeconds()
     struct timespec ts;
     clock_gettime(CLOCK_MONOTONIC, &ts);
     currentTime = ts.tv_sec * USECS_PER_SEC + ts.tv_nsec / 1000;
+#elif defined(_WIN32)
+    struct __timeb64 tb;
+    _ftime64_s(&tb);
+    currentTime = tb.time * USECS_PER_SEC + tb.millitm * MSECS_PER_SEC;
 #else
     struct timeval tv;
     gettimeofday(&tv, NULL);
index 5cc3798..8706ecf 100644 (file)
@@ -48,6 +48,9 @@ if target_os in ['linux','darwin','ios']:
     target_files += [ os.path.join(src_dir,
                                    'linux/caipnwmonitor.c') ]
 
+if target_os in ['msys_nt']:
+       target_files += [ os.path.join(src_dir, 'windows/caipnwmonitor.c') ]
+
 # The list of BLE adapter source files is a combination of both the
 # common and target-specific source file lists.
 env.AppendUnique(CA_SRC = common_files + target_files)
index ff70009..0809c8d 100644 (file)
@@ -213,7 +213,6 @@ u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
     caglobals.ip.nm.numIfItems = 0;
     for (size_t i = 0; i < interfaces; i++)
     {
-        CAResult_t result = CA_STATUS_OK;
         struct ifreq* item = &ifr[i];
         char *name = item->ifr_name;
         struct sockaddr_in *sa4 = (struct sockaddr_in *)&item->ifr_addr;
@@ -245,7 +244,7 @@ u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
         }
 
         // Add IPv4 interface
-        result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET, ipv4addr, flags);
+        CAResult_t result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET, ipv4addr, flags);
         if (CA_STATUS_OK != result)
         {
             goto exit;
@@ -321,7 +320,7 @@ CAResult_t CAIPJniInit()
         return CA_STATUS_FAILED;
     }
 
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     if ((*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
     {
         OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
@@ -380,7 +379,7 @@ static CAResult_t CAIPDestroyJniInterface()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
index 98c7e5f..b014254 100644 (file)
@@ -367,7 +367,7 @@ CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
 
         eps[j].flags = CA_IPV4;
         eps[j].adapter = CA_ADAPTER_IP;
-        eps[j].interface = 0;
+        eps[j].ifindex = 0;
         eps[j].port = caglobals.ip.u4.port;
         j++;
     }
index 2ad25fe..48d52e2 100644 (file)
@@ -304,7 +304,7 @@ CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
 
         eps[j].flags = CA_IPV4;
         eps[j].adapter = CA_ADAPTER_IP;
-        eps[j].interface = 0;
+        eps[j].ifindex = 0;
         eps[j].port = caglobals.ip.u4.port;
         j++;
     }
index 10613af..e77f46d 100644 (file)
@@ -272,6 +272,12 @@ CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback,
 
 CAResult_t CAStartIP()
 {
+    // Specific the port number received from application.
+    caglobals.ip.u6.port  = caglobals.ports.udp.u6;
+    caglobals.ip.u6s.port = caglobals.ports.udp.u6s;
+    caglobals.ip.u4.port  = caglobals.ports.udp.u4;
+    caglobals.ip.u4s.port = caglobals.ports.udp.u4s;
+
     CAIPStartNetworkMonitor();
 #ifdef SINGLE_THREAD
     uint16_t unicastPort = 55555;
index 7609199..7e9d2cc 100644 (file)
@@ -1,4 +1,4 @@
-/*****************************************************************j
+/* ****************************************************************
  *
  * Copyright 2014 Samsung Electronics All Rights Reserved.
  *
 #endif
 
 #include <sys/types.h>
+#if !defined(_WIN32)
 #include <sys/socket.h>
+#endif
+
+#if defined(_WIN32)
+#include <assert.h>
+#include <winsock2.h>
+#include <ws2def.h>
+#include <mswsock.h>
+#include <ws2tcpip.h>
+#endif
+
 #include <stdio.h>
+#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>
 #include <arpa/inet.h>
 #include <netinet/in.h>
 #include <net/if.h>
+#endif
 #include <errno.h>
 #ifdef __linux__
 #include <linux/netlink.h>
 #include "camutex.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
+#include "platform_features.h"
+
+#define USE_IP_MREQN
+#if defined(_WIN32)
+#undef USE_IP_MREQN
+#endif
 
 /*
  * Logging tag for module name
@@ -96,63 +117,67 @@ static char *ipv6mcnames[IPv6_DOMAINS] = {
     NULL
 };
 
-static CAIPPacketReceivedCallback g_packetReceivedCallback = NULL;
+#if defined (_WIN32)
+#define IFF_UP_RUNNING_FLAGS  (IFF_UP)
 
+    char* caips_get_error(){
+        static char buffer[32];
+        snprintf(buffer, 32, "%i", WSAGetLastError());
+        return buffer;
+    }
+#define CAIPS_GET_ERROR \
+    caips_get_error()
+#else
+#define IFF_UP_RUNNING_FLAGS  (IFF_UP|IFF_RUNNING)
+
+#define CAIPS_GET_ERROR \
+    strerror(errno)
+#endif
 static CAIPErrorHandleCallback g_ipErrorHandler = NULL;
 
-static void CAHandleNetlink();
+static CAIPPacketReceivedCallback g_packetReceivedCallback = NULL;
+
 static void CAFindReadyMessage();
+#if !defined(WSA_WAIT_EVENT_0)
 static void CASelectReturned(fd_set *readFds, int ret);
+#else
+static void CAEventReturned(CASocketFd_t socket);
+#endif
 static void CAProcessNewInterface(CAInterface_t *ifchanged);
-static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags);
+static CAResult_t CAReceiveMessage(CASocketFd_t fd, CATransportFlags_t flags);
 
-#define SET(TYPE, FDS) \
-    if (caglobals.ip.TYPE.fd != -1) \
-    { \
-        FD_SET(caglobals.ip.TYPE.fd, FDS); \
-    }
+static void CAReceiveHandler(void *data)
+{
+    (void)data;
 
-#define ISSET(TYPE, FDS, FLAGS) \
-    if (caglobals.ip.TYPE.fd != -1 && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
-    { \
-        fd = caglobals.ip.TYPE.fd; \
-        flags = FLAGS; \
+    while (!caglobals.ip.terminate)
+    {
+        CAFindReadyMessage();
     }
+}
+
+#if !defined(WSA_WAIT_EVENT_0)
 
 #define CLOSE_SOCKET(TYPE) \
-    if (caglobals.ip.TYPE.fd != -1) \
+    if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
     { \
         close(caglobals.ip.TYPE.fd); \
-        caglobals.ip.TYPE.fd = -1; \
+        caglobals.ip.TYPE.fd = OC_INVALID_SOCKET; \
     }
 
-void CADeInitializeIPGlobals()
-{
-    CLOSE_SOCKET(u6);
-    CLOSE_SOCKET(u6s);
-    CLOSE_SOCKET(u4);
-    CLOSE_SOCKET(u4s);
-    CLOSE_SOCKET(m6);
-    CLOSE_SOCKET(m6s);
-    CLOSE_SOCKET(m4);
-    CLOSE_SOCKET(m4s);
-
-    if (caglobals.ip.netlinkFd != -1)
-    {
-        close(caglobals.ip.netlinkFd);
-        caglobals.ip.netlinkFd = -1;
+#define SET(TYPE, FDS) \
+    if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
+    { \
+        FD_SET(caglobals.ip.TYPE.fd, FDS); \
     }
-}
-
-static void CAReceiveHandler(void *data)
-{
-    (void)data;
 
-    while (!caglobals.ip.terminate)
-    {
-        CAFindReadyMessage();
+#define ISSET(TYPE, FDS, FLAGS) \
+    if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
+    { \
+        fd = caglobals.ip.TYPE.fd; \
+        flags = FLAGS; \
     }
-}
+
 
 static void CAFindReadyMessage()
 {
@@ -172,11 +197,12 @@ static void CAFindReadyMessage()
     SET(m6s, &readFds)
     SET(m4,  &readFds)
     SET(m4s, &readFds)
+
     if (caglobals.ip.shutdownFds[0] != -1)
     {
         FD_SET(caglobals.ip.shutdownFds[0], &readFds);
     }
-    if (caglobals.ip.netlinkFd != -1)
+    if (caglobals.ip.netlinkFd != OC_INVALID_SOCKET)
     {
         FD_SET(caglobals.ip.netlinkFd, &readFds);
     }
@@ -188,11 +214,12 @@ static void CAFindReadyMessage()
         OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
         return;
     }
+
     if (ret <= 0)
     {
         if (ret < 0)
         {
-            OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
+            OIC_LOG_V(FATAL, TAG, "select error %s", CAIPS_GET_ERROR);
         }
         return;
     }
@@ -203,7 +230,7 @@ static void CAFindReadyMessage()
 static void CASelectReturned(fd_set *readFds, int ret)
 {
     (void)ret;
-    int fd = -1;
+    CASocketFd_t fd = OC_INVALID_SOCKET;
     CATransportFlags_t flags = CA_DEFAULT_FLAGS;
 
     while (!caglobals.ip.terminate)
@@ -216,7 +243,7 @@ static void CASelectReturned(fd_set *readFds, int ret)
         else ISSET(m6s, readFds, CA_MULTICAST | CA_IPV6 | CA_SECURE)
         else ISSET(m4,  readFds, CA_MULTICAST | CA_IPV4)
         else ISSET(m4s, readFds, CA_MULTICAST | CA_IPV4 | CA_SECURE)
-        else if (FD_ISSET(caglobals.ip.netlinkFd, readFds))
+        else if ((caglobals.ip.netlinkFd != OC_INVALID_SOCKET) && FD_ISSET(caglobals.ip.netlinkFd, readFds))
         {
             CAInterface_t *ifchanged = CAFindInterfaceChange();
             if (ifchanged)
@@ -240,22 +267,231 @@ static void CASelectReturned(fd_set *readFds, int ret)
         {
             break;
         }
-
         (void)CAReceiveMessage(fd, flags);
         FD_CLR(fd, readFds);
     }
 }
 
-static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
+#else // if defined(WSA_WAIT_EVENT_0)
+
+#define CLOSE_SOCKET(TYPE) \
+    if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
+    { \
+        closesocket(caglobals.ip.TYPE.fd); \
+        caglobals.ip.TYPE.fd = OC_INVALID_SOCKET; \
+    }
+
+#define PUSH_HANDLE(HANDLE, ARRAY, INDEX) \
+{ \
+    ARRAY[INDEX] = HANDLE; \
+    INDEX++; \
+}
+
+// Turn handle into WSAEvent and push to ARRAY
+#define PUSH_SOCKET(SOCKET, ARRAY, INDEX) \
+    if (SOCKET != OC_INVALID_SOCKET) \
+    { \
+        WSAEVENT NewEvent; \
+        NewEvent = WSACreateEvent(); \
+        if (WSA_INVALID_EVENT != NewEvent) \
+        { \
+            if (0 != WSAEventSelect(SOCKET, NewEvent, FD_READ)) \
+            { \
+                OIC_LOG_V(ERROR, TAG, "WSAEventSelect failed 0x%08x ", WSAGetLastError()); \
+                if (!WSACloseEvent(NewEvent)) \
+                { \
+                    OIC_LOG_V(ERROR, TAG, "WSACloseEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
+                } \
+            } \
+            else \
+            { \
+                PUSH_HANDLE(NewEvent, ARRAY, INDEX); \
+            } \
+        } \
+        else \
+        { \
+            OIC_LOG_V(ERROR, TAG, "WSACreateEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
+        }\
+    }
+
+#define INSERT_SOCKET(FD, ARRAY, INDEX) \
+    { \
+        if (OC_INVALID_SOCKET != FD) \
+        { \
+            ARRAY[INDEX] = FD; \
+        } \
+    }
+
+
+// Inserts the socket into the SOCKET_ARRAY and pushes the socket event into EVENT_ARRAY
+#define PUSH_IP_SOCKET(TYPE, EVENT_ARRAY, SOCKET_ARRAY, INDEX) \
+    { \
+        if (OC_INVALID_SOCKET != caglobals.ip.TYPE.fd) \
+        { \
+            INSERT_SOCKET(caglobals.ip.TYPE.fd, SOCKET_ARRAY, INDEX); \
+            PUSH_SOCKET(caglobals.ip.TYPE.fd, EVENT_ARRAY, INDEX); \
+        } \
+    }
+
+#define IS_MATCHING_IP_SOCKET(TYPE, SOCKET, FLAGS) \
+    if ((caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) && (caglobals.ip.TYPE.fd == SOCKET)) \
+    { \
+        fd = caglobals.ip.TYPE.fd; \
+        flags = FLAGS; \
+    }
+
+#define EVENT_ARRAY_SIZE  10
+
+static void CAFindReadyMessage()
 {
-    char recvBuffer[COAP_MAX_PDU_SIZE];
+    CASocketFd_t socketArray[EVENT_ARRAY_SIZE];
+    HANDLE eventArray[EVENT_ARRAY_SIZE];
+    int arraySize = 0;
+    int eventIndex;
+
+    // socketArray and eventArray should have same number of elements
+    OC_STATIC_ASSERT(_countof(socketArray) == _countof(eventArray), "Arrays should have same number of elements");
+
+    PUSH_IP_SOCKET(u6,  eventArray, socketArray, arraySize);
+    PUSH_IP_SOCKET(u6s, eventArray, socketArray, arraySize);
+    PUSH_IP_SOCKET(u4,  eventArray, socketArray, arraySize);
+    PUSH_IP_SOCKET(u4s, eventArray, socketArray, arraySize);
+    PUSH_IP_SOCKET(m6,  eventArray, socketArray, arraySize);
+    PUSH_IP_SOCKET(m6s, eventArray, socketArray, arraySize);
+    PUSH_IP_SOCKET(m4,  eventArray, socketArray, arraySize);
+    PUSH_IP_SOCKET(m4s, eventArray, socketArray, arraySize);
+
+    if (-1 != caglobals.ip.shutdownEvent)
+    {
+        INSERT_SOCKET(OC_INVALID_SOCKET, socketArray, arraySize);
+        PUSH_HANDLE(caglobals.ip.shutdownEvent, eventArray, arraySize);
+    }
+
+    /** @todo Support netlink events */
+
+    // Should not have overflowed buffer
+    assert(arraySize <= (_countof(socketArray)));
+
+    // Timeout is unnecessary on Windows
+    assert(-1 == caglobals.ip.selectTimeout);
+
+    while (!caglobals.ip.terminate)
+    {
+        int ret = WSAWaitForMultipleEvents(arraySize, eventArray, FALSE, WSA_INFINITE, FALSE);
+
+        switch (ret)
+        {
+            case WSA_WAIT_FAILED:
+                OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_FAILED 0x%08x", WSAGetLastError());
+                break;
+            case WSA_WAIT_IO_COMPLETION:
+                OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_IO_COMPLETION 0x%08x", WSAGetLastError());
+                break;
+            case WSA_WAIT_TIMEOUT:
+                OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_TIMEOUT 0x%08x", WSAGetLastError());
+                break;
+            default:
+                eventIndex = ret - WSA_WAIT_EVENT_0;
+                if ((eventIndex >= 0) && (eventIndex < arraySize))
+                {
+                    if (false == WSAResetEvent(eventArray[eventIndex]))
+                    {
+                        OIC_LOG_V(ERROR, TAG, "WSAResetEvent failed 0x%08x", WSAGetLastError());
+                    }
+
+                    // Break out if shutdownEvent is triggered
+                    if ((caglobals.ip.shutdownEvent != -1) &&
+                        (caglobals.ip.shutdownEvent == eventArray[eventIndex]))
+                    {
+                        break;
+                    }
+                    CAEventReturned(socketArray[eventIndex]);
+                }
+                else
+                {
+                    OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents failed 0x%08x", WSAGetLastError());
+                }
+                break;
+        }
+
+    }
+
+    while (arraySize > 0)
+    {
+        arraySize--;
+        if (!WSACloseEvent(eventArray[arraySize]))
+        {
+            OIC_LOG_V(ERROR, TAG, "WSACloseEvent (Index %i) failed 0x%08x", arraySize, WSAGetLastError());
+        }
+    }
+
+    if (caglobals.ip.terminate)
+    {
+        caglobals.ip.shutdownEvent = -1;
+        WSACleanup();
+    }
+}
+
+static void CAEventReturned(CASocketFd_t socket)
+{
+    CASocketFd_t fd = OC_INVALID_SOCKET;
+    CATransportFlags_t flags = CA_DEFAULT_FLAGS;
+
+    while (!caglobals.ip.terminate)
+    {
+        IS_MATCHING_IP_SOCKET(u6,  socket, CA_IPV6)
+        else IS_MATCHING_IP_SOCKET(u6s, socket, CA_IPV6 | CA_SECURE)
+        else IS_MATCHING_IP_SOCKET(u4,  socket, CA_IPV4)
+        else IS_MATCHING_IP_SOCKET(u4s, socket, CA_IPV4 | CA_SECURE)
+        else IS_MATCHING_IP_SOCKET(m6,  socket, CA_MULTICAST | CA_IPV6)
+        else IS_MATCHING_IP_SOCKET(m6s, socket, CA_MULTICAST | CA_IPV6 | CA_SECURE)
+        else IS_MATCHING_IP_SOCKET(m4,  socket, CA_MULTICAST | CA_IPV4)
+        else IS_MATCHING_IP_SOCKET(m4s, socket, CA_MULTICAST | CA_IPV4 | CA_SECURE)
+        else
+        {
+            break;
+        }
+        (void)CAReceiveMessage(socket, flags);
+        // We will never get more than one match per socket, so always break.
+        break;
+    }
+}
+
+#endif
+
+void CADeInitializeIPGlobals()
+{
+    CLOSE_SOCKET(u6);
+    CLOSE_SOCKET(u6s);
+    CLOSE_SOCKET(u4);
+    CLOSE_SOCKET(u4s);
+    CLOSE_SOCKET(m6);
+    CLOSE_SOCKET(m6s);
+    CLOSE_SOCKET(m4);
+    CLOSE_SOCKET(m4s);
+
+    if (caglobals.ip.netlinkFd != OC_INVALID_SOCKET)
+    {
+#ifdef _WIN32
+        closesocket(caglobals.ip.netlinkFd);
+#else
+        close(caglobals.ip.netlinkFd);
+#endif
+        caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
+    }
+}
+
+static CAResult_t CAReceiveMessage(CASocketFd_t fd, CATransportFlags_t flags)
+{
+    char recvBuffer[COAP_MAX_PDU_SIZE] = {0};
 
     size_t len;
     int level, type, namelen;
     struct sockaddr_storage srcAddr;
     unsigned char *pktinfo = NULL;
+#if !defined(WSA_CMSG_DATA)
     struct cmsghdr *cmp = NULL;
-    struct iovec iov = { recvBuffer, sizeof (recvBuffer) };
+    struct iovec iov = { .iov_base = recvBuffer, .iov_len = sizeof (recvBuffer) };
     union control
     {
         struct cmsghdr cmsg;
@@ -285,7 +521,7 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
                           .msg_controllen = CMSG_SPACE(len) };
 
     ssize_t recvLen = recvmsg(fd, &msg, flags);
-    if (-1 == recvLen)
+    if (OC_SOCKET_ERROR == recvLen)
     {
         OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
         return CA_STATUS_FAILED;
@@ -301,14 +537,60 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
             }
         }
     }
+#else // if defined(WSA_CMSG_DATA)
+    union control
+    {
+        WSACMSGHDR cmsg;
+        uint8_t data[WSA_CMSG_SPACE(sizeof (IN6_PKTINFO))];
+    } cmsg;
+    memset(&cmsg, 0, sizeof(cmsg));
+
+    if (flags & CA_IPV6)
+    {
+        namelen  = sizeof (struct sockaddr_in6);
+        level = IPPROTO_IPV6;
+        type = IPV6_PKTINFO;
+    }
+    else
+    {
+        namelen = sizeof (struct sockaddr_in);
+        level = IPPROTO_IP;
+        type = IP_PKTINFO;
+    }
 
+    WSABUF iov = {.len = sizeof (recvBuffer), .buf = recvBuffer};
+    WSAMSG msg = {.name = &srcAddr,
+                  .namelen = namelen,
+                  .lpBuffers = &iov,
+                  .dwBufferCount = 1,
+                  .Control = {.buf = cmsg.data, .len = sizeof (cmsg)}
+                 };
+
+    uint32_t recvLen = 0;
+    uint32_t ret = caglobals.ip.wsaRecvMsg(fd, &msg, &recvLen, 0,0);
+    OIC_LOG_V(DEBUG, TAG, "WSARecvMsg recvd %u bytes", recvLen);
+    if (OC_SOCKET_ERROR == ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "WSARecvMsg failed %i", WSAGetLastError());
+    }
+
+    if (flags & CA_MULTICAST)
+    {
+        for (WSACMSGHDR *cmp = WSA_CMSG_FIRSTHDR(&msg); cmp != NULL;
+             cmp = WSA_CMSG_NXTHDR(&msg, cmp))
+        {
+            if (cmp->cmsg_level == level && cmp->cmsg_type == type)
+            {
+                pktinfo = WSA_CMSG_DATA(cmp);
+            }
+        }
+    }
+#endif // !defined(WSA_CMSG_DATA)
     CASecureEndpoint_t sep = {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};
 
     if (flags & CA_IPV6)
     {
-        sep.endpoint.interface = ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id;
-        ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id = 0;
-
+        /** @todo figure out correct usage for ifindex, and sin6_scope_id.*/
         if ((flags & CA_MULTICAST) && pktinfo)
         {
             struct in6_addr *addr = &(((struct in6_pktinfo *)pktinfo)->ipi6_addr);
@@ -333,7 +615,7 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
         }
     }
 
-    CAConvertAddrToName(&srcAddr, msg.msg_namelen, sep.endpoint.addr, &sep.endpoint.port);
+    CAConvertAddrToName(&srcAddr, namelen, sep.endpoint.addr, &sep.endpoint.port);
 
     if (flags & CA_SECURE)
     {
@@ -353,6 +635,7 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
     }
 
     return CA_STATUS_OK;
+
 }
 
 void CAIPPullData()
@@ -361,29 +644,28 @@ void CAIPPullData()
     OIC_LOG(DEBUG, TAG, "OUT");
 }
 
-static int CACreateSocket(int family, uint16_t *port)
+static CASocketFd_t CACreateSocket(int family, uint16_t *port, bool isMulticast)
 {
     int socktype = SOCK_DGRAM;
 #ifdef SOCK_CLOEXEC
     socktype |= SOCK_CLOEXEC;
 #endif
-    int fd = socket(family, socktype, IPPROTO_UDP);
-    if (-1 == fd)
+    CASocketFd_t fd = socket(family, socktype, IPPROTO_UDP);
+    if (OC_INVALID_SOCKET == fd)
     {
-        OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
-        return -1;
+        OIC_LOG_V(ERROR, TAG, "create socket failed: %s", CAIPS_GET_ERROR);
+        return OC_INVALID_SOCKET;
     }
 
-#ifndef SOCK_CLOEXEC
+#if !defined(SOCK_CLOEXEC) && defined(FD_CLOEXEC)
     int fl = fcntl(fd, F_GETFD);
     if (-1 == fl || -1 == fcntl(fd, F_SETFD, fl|FD_CLOEXEC))
     {
         OIC_LOG_V(ERROR, TAG, "set FD_CLOEXEC failed: %s", strerror(errno));
         close(fd);
-        return -1;
+        return OC_INVALID_SOCKET;
     }
 #endif
-
     struct sockaddr_storage sa = { .ss_family = family };
     socklen_t socklen;
 
@@ -391,16 +673,20 @@ static int CACreateSocket(int family, uint16_t *port)
     {
         int on = 1;
 
-        if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
+        if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&on), sizeof (on)))
         {
-            OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
+            OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", CAIPS_GET_ERROR);
         }
 
-        if (*port)      // only do this for multicast ports
+        if (isMulticast && *port) // only do this for multicast ports
         {
-            if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
+#if defined(IPV6_RECVPKTINFO)
+            if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
+#else
+            if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, OPTVAL_T(&on), sizeof (on)))
+#endif
             {
-                OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s", strerror(errno));
+                OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s",CAIPS_GET_ERROR);
             }
         }
 
@@ -409,12 +695,12 @@ static int CACreateSocket(int family, uint16_t *port)
     }
     else
     {
-        if (*port)      // only do this for multicast ports
+        if (isMulticast && *port) // only do this for multicast ports
         {
             int on = 1;
-            if (-1 == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &on, sizeof (on)))
+            if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, OPTVAL_T(&on), sizeof (on)))
             {
-                OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", strerror(errno));
+                OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", CAIPS_GET_ERROR);
             }
         }
 
@@ -422,31 +708,43 @@ static int CACreateSocket(int family, uint16_t *port)
         socklen = sizeof (struct sockaddr_in);
     }
 
-    if (*port)  // use the given port
+    if (isMulticast && *port) // use the given port
     {
         int on = 1;
-        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof (on)))
+        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
         {
-            OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
+            OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", CAIPS_GET_ERROR);
+#ifdef _WIN32
+            closesocket(fd);
+#else
             close(fd);
-            return -1;
+#endif
+            return OC_INVALID_SOCKET;
         }
     }
 
-    if (-1 == bind(fd, (struct sockaddr *)&sa, socklen))
+    if (OC_SOCKET_ERROR == bind(fd, (struct sockaddr *)&sa, socklen))
     {
-        OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
+        OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", CAIPS_GET_ERROR);
+#ifdef _WIN32
+        closesocket(fd);
+#else
         close(fd);
-        return -1;
+#endif
+        return OC_INVALID_SOCKET;
     }
 
-    if (!*port)  // return the assigned port
+    if (!*port) // return the assigned port
     {
-        if (-1 == getsockname(fd, (struct sockaddr *)&sa, &socklen))
+        if (OC_SOCKET_ERROR == getsockname(fd, (struct sockaddr *)&sa, &socklen))
         {
-            OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
+            OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", CAIPS_GET_ERROR);
+#ifdef _WIN32
+            closesocket(fd);
+#else
             close(fd);
-            return -1;
+#endif
+            return OC_INVALID_SOCKET;
         }
         *port = ntohs(family == AF_INET6 ?
                       ((struct sockaddr_in6 *)&sa)->sin6_port :
@@ -459,18 +757,24 @@ static int CACreateSocket(int family, uint16_t *port)
 #define CHECKFD(FD) \
     if (FD > caglobals.ip.maxfd) \
         caglobals.ip.maxfd = FD;
-#define NEWSOCKET(FAMILY, NAME) \
-    caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port); \
+#define NEWSOCKET(FAMILY, NAME, MULTICAST) \
+    caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port, MULTICAST); \
+    if (caglobals.ip.NAME.fd == OC_INVALID_SOCKET) \
+    {   \
+        caglobals.ip.NAME.port = 0; \
+        caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port, MULTICAST); \
+    }   \
     CHECKFD(caglobals.ip.NAME.fd)
 
 static void CAInitializeNetlink()
 {
+    caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
 #ifdef __linux__
     // create NETLINK fd for interface change notifications
     struct sockaddr_nl sa = { AF_NETLINK, 0, 0, RTMGRP_LINK };
 
     caglobals.ip.netlinkFd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_ROUTE);
-    if (caglobals.ip.netlinkFd == -1)
+    if (caglobals.ip.netlinkFd == OC_INVALID_SOCKET)
     {
         OIC_LOG_V(ERROR, TAG, "netlink socket failed: %s", strerror(errno));
     }
@@ -481,7 +785,7 @@ static void CAInitializeNetlink()
         {
             OIC_LOG_V(ERROR, TAG, "netlink bind failed: %s", strerror(errno));
             close(caglobals.ip.netlinkFd);
-            caglobals.ip.netlinkFd = -1;
+            caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
         }
         else
         {
@@ -491,13 +795,28 @@ static void CAInitializeNetlink()
 #endif
 }
 
-static void CAInitializePipe()
+static void CAInitializeFastShutdownMechanism()
 {
-    caglobals.ip.selectTimeout = -1;
-#ifdef HAVE_PIPE2
-    int ret = pipe2(caglobals.ip.shutdownFds, O_CLOEXEC);
+    caglobals.ip.selectTimeout = -1; // don't poll for shutdown
+    int ret = -1;
+#if defined(WSA_WAIT_EVENT_0)
+    caglobals.ip.shutdownEvent = -1;
+    caglobals.ip.shutdownEvent = WSACreateEvent();
+
+    if (caglobals.ip.shutdownEvent == WSA_INVALID_EVENT)
+    {
+        caglobals.ip.shutdownEvent = -1;
+    }
+    else
+    {
+        ret = 0;
+    }
+#elif defined(HAVE_PIPE2)
+    ret = pipe2(caglobals.ip.shutdownFds, O_CLOEXEC);
+    CHECKFD(caglobals.ip.shutdownFds[0]);
+    CHECKFD(caglobals.ip.shutdownFds[1]);
 #else
-    int ret = pipe(caglobals.ip.shutdownFds);
+    ret = pipe(caglobals.ip.shutdownFds);
     if (-1 != ret)
     {
         ret = fcntl(caglobals.ip.shutdownFds[0], F_GETFD);
@@ -521,10 +840,12 @@ static void CAInitializePipe()
             caglobals.ip.shutdownFds[1] = -1;
         }
     }
+    CHECKFD(caglobals.ip.shutdownFds[0]);
+    CHECKFD(caglobals.ip.shutdownFds[1]);
 #endif
     if (-1 == ret)
     {
-        OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
+        OIC_LOG_V(ERROR, TAG, "fast shutdown mechanism init failed: %s", CAIPS_GET_ERROR);
         caglobals.ip.selectTimeout = SELECT_TIMEOUT; //poll needed for shutdown
     }
 }
@@ -537,7 +858,17 @@ CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
     {
         return res;
     }
-
+#if defined (_WIN32)
+    WORD wVersionRequested = MAKEWORD(2, 2);
+    WSADATA wsaData ={.wVersion = 0};
+    int err = WSAStartup(wVersionRequested, &wsaData);
+    if (err != 0)
+    {
+        OIC_LOG_V(ERROR, TAG, "WSAStartup failed: %i", err);
+        return CA_STATUS_FAILED;
+    }
+    OIC_LOG(DEBUG, TAG, "WSAStartup Succeeded");
+#endif
     if (!IPv4MulticastAddress.s_addr)
     {
         (void)inet_pton(AF_INET, IPv4_MULTICAST, &IPv4MulticastAddress);
@@ -557,18 +888,18 @@ CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
 
     if (caglobals.ip.ipv6enabled)
     {
-        NEWSOCKET(AF_INET6, u6)
-        NEWSOCKET(AF_INET6, u6s)
-        NEWSOCKET(AF_INET6, m6)
-        NEWSOCKET(AF_INET6, m6s)
+        NEWSOCKET(AF_INET6, u6, false)
+        NEWSOCKET(AF_INET6, u6s, false)
+        NEWSOCKET(AF_INET6, m6, true)
+        NEWSOCKET(AF_INET6, m6s, true)
         OIC_LOG_V(INFO, TAG, "IPv6 unicast port: %u", caglobals.ip.u6.port);
     }
     if (caglobals.ip.ipv4enabled)
     {
-        NEWSOCKET(AF_INET, u4)
-        NEWSOCKET(AF_INET, u4s)
-        NEWSOCKET(AF_INET, m4)
-        NEWSOCKET(AF_INET, m4s)
+        NEWSOCKET(AF_INET, u4, false)
+        NEWSOCKET(AF_INET, u4s, false)
+        NEWSOCKET(AF_INET, m4, true)
+        NEWSOCKET(AF_INET, m4s, true)
         OIC_LOG_V(INFO, TAG, "IPv4 unicast port: %u", caglobals.ip.u4.port);
     }
 
@@ -583,10 +914,19 @@ CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
               caglobals.ip.u6.port, caglobals.ip.u6s.port, caglobals.ip.u4.port,
               caglobals.ip.u4s.port, caglobals.ip.m6.port, caglobals.ip.m6s.port,
               caglobals.ip.m4.port, caglobals.ip.m4s.port);
-    // create pipe for fast shutdown
-    CAInitializePipe();
-    CHECKFD(caglobals.ip.shutdownFds[0]);
-    CHECKFD(caglobals.ip.shutdownFds[1]);
+#if defined (SIO_GET_EXTENSION_FUNCTION_POINTER)
+    caglobals.ip.wsaRecvMsg = NULL;
+    GUID GuidWSARecvMsg = WSAID_WSARECVMSG;
+    DWORD copied = 0;
+    err = WSAIoctl(caglobals.ip.u4.fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidWSARecvMsg, sizeof(GuidWSARecvMsg), &(caglobals.ip.wsaRecvMsg), sizeof(caglobals.ip.wsaRecvMsg), &copied, 0, 0);
+    if (0 != err)
+    {
+        OIC_LOG_V(ERROR, TAG, "WSAIoctl failed %i", WSAGetLastError());
+        return CA_STATUS_FAILED;
+    }
+#endif
+    // set up appropriate FD mechanism for fast shutdown
+    CAInitializeFastShutdownMechanism();
 
     // create source of network interface change notifications
     CAInitializeNetlink();
@@ -618,6 +958,7 @@ void CAIPStopServer()
     caglobals.ip.started = false;
     caglobals.ip.terminate = true;
 
+#if !defined(WSA_WAIT_EVENT_0)
     if (caglobals.ip.shutdownFds[1] != -1)
     {
         close(caglobals.ip.shutdownFds[1]);
@@ -627,10 +968,18 @@ void CAIPStopServer()
     {
         // receive thread will stop in SELECT_TIMEOUT seconds.
     }
+#else
+    // receive thread will stop immediately.
+    if (!WSASetEvent(caglobals.ip.shutdownEvent))
+    {
+        OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
+    }
+#endif
 }
 
 void CAWakeUpForChange()
 {
+#if !defined(WSA_WAIT_EVENT_0)
     if (caglobals.ip.shutdownFds[1] != -1)
     {
         ssize_t len = 0;
@@ -643,68 +992,95 @@ void CAWakeUpForChange()
             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
         }
     }
+#else
+    if (!WSASetEvent(caglobals.ip.shutdownEvent))
+    {
+        OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
+    }
+#endif
 }
 
-static void applyMulticastToInterface4(struct in_addr inaddr)
+static void applyMulticastToInterface4(uint32_t ifindex)
 {
     if (!caglobals.ip.ipv4enabled)
     {
         return;
     }
 
+#if defined(USE_IP_MREQN)
     struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
-                             .imr_address = inaddr,
-                             .imr_ifindex = 0 };
-    if (setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
+                             .imr_address.s_addr = htonl(INADDR_ANY),
+                             .imr_ifindex = ifindex };
+#else
+    struct ip_mreq mreq  = { .imr_multiaddr = IPv4MulticastAddress,
+                             .imr_interface.s_addr = htonl(ifindex) };
+#endif
+
+    int ret = setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, OPTVAL_T(&mreq), sizeof (mreq));
+    if (OC_SOCKET_ERROR == ret)
     {
+#if !defined(WSAEINVAL)
         if (EADDRINUSE != errno)
+#else
+        if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
+#endif
         {
-            OIC_LOG_V(ERROR, TAG, "IPv4 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
+            OIC_LOG_V(ERROR, TAG, "       IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
         }
     }
-    if (setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
+    ret = setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, OPTVAL_T(&mreq), sizeof (mreq));
+    if (OC_SOCKET_ERROR == ret)
     {
+#if !defined(WSAEINVAL)
         if (EADDRINUSE != errno)
+#else
+        if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
+#endif
         {
-            OIC_LOG_V(ERROR, TAG, "secure IPv4 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
+            OIC_LOG_V(ERROR, TAG, "SECURE IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
         }
     }
 }
 
-static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t interface)
+static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t ifindex)
 {
-    struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr, .ipv6mr_interface = interface};
-
-    if (setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof (mreq)))
+    struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr,
+                             .ipv6mr_interface = ifindex };
+    int ret = setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, OPTVAL_T(&mreq), sizeof (mreq));
+    if (OC_SOCKET_ERROR == ret)
     {
-        if (EADDRINUSE != errno)
+#if !defined(_WIN32)
+                if (EADDRINUSE != errno)
+#else
+                if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv6 Flavor)
+#endif
         {
-            OIC_LOG_V(ERROR, TAG, "IPv6 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
+            OIC_LOG_V(ERROR, TAG, "IPv6 IPV6_JOIN_GROUP failed: %s", CAIPS_GET_ERROR);
         }
     }
 }
 
-static void applyMulticastToInterface6(uint32_t interface)
+static void applyMulticastToInterface6(uint32_t ifindex)
 {
     if (!caglobals.ip.ipv6enabled)
     {
         return;
     }
-    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, interface);
-    applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, interface);
-    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, interface);
-    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, interface);
-    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, interface);
-    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, interface);
-    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, interface);
-
-    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, interface);
-    applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, interface);
-    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, interface);
-    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, interface);
-    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, interface);
-    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, interface);
-    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, interface);
+    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, ifindex);
+    applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, ifindex);
+    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, ifindex);
+    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, ifindex);
+    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, ifindex);
+    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, ifindex);
+    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, ifindex);
+
+    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, ifindex);
+    applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, ifindex);
+    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, ifindex);
+    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, ifindex);
+    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, ifindex);
+    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, ifindex);
+    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, ifindex);
 }
 
 CAResult_t CAIPStartListenServer()
@@ -712,7 +1088,7 @@ CAResult_t CAIPStartListenServer()
     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
     if (!iflist)
     {
-        OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
+        OIC_LOG_V(ERROR, TAG, "CAIPGetInterfaceInformation() failed: %s", strerror(errno));
         return CA_STATUS_FAILED;
     }
 
@@ -727,21 +1103,19 @@ CAResult_t CAIPStartListenServer()
         {
             continue;
         }
-        if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
+        if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
         {
             continue;
         }
         if (ifitem->family == AF_INET)
         {
-            struct in_addr inaddr;
-            inaddr.s_addr = ifitem->ipv4addr;
-            applyMulticastToInterface4(inaddr);
-            OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s", ifitem->name);
+            OIC_LOG_V(DEBUG, TAG, "Adding IPv4 interface %i to multicast group", ifitem->index);
+            applyMulticastToInterface4(ifitem->index);
         }
         if (ifitem->family == AF_INET6)
         {
+            OIC_LOG_V(DEBUG, TAG, "Adding IPv6 interface %i to multicast group", ifitem->index);
             applyMulticastToInterface6(ifitem->index);
-            OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
         }
     }
 
@@ -769,25 +1143,20 @@ CAResult_t CAIPStopListenServer()
         {
             continue;
         }
-
-        if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
+        if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
         {
             continue;
         }
         if (ifitem->family == AF_INET)
         {
-            close(caglobals.ip.m4.fd);
-            close(caglobals.ip.m4s.fd);
-            caglobals.ip.m4.fd = -1;
-            caglobals.ip.m4s.fd = -1;
+            CLOSE_SOCKET(m4);
+            CLOSE_SOCKET(m4s);
             OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s cloed", ifitem->name);
         }
         if (ifitem->family == AF_INET6)
         {
-            close(caglobals.ip.m6.fd);
-            close(caglobals.ip.m6s.fd);
-            caglobals.ip.m6.fd = -1;
-            caglobals.ip.m6s.fd = -1;
+            CLOSE_SOCKET(m6);
+            CLOSE_SOCKET(m6s);
             OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
         }
     }
@@ -802,14 +1171,14 @@ static void CAProcessNewInterface(CAInterface_t *ifitem)
         OIC_LOG(DEBUG, TAG, "ifitem is null");
         return;
     }
+
     if (ifitem->family == AF_INET6)
     {
         applyMulticastToInterface6(ifitem->index);
     }
     if (ifitem->family == AF_INET)
     {
-        struct in_addr inaddr = { .s_addr = ifitem->ipv4addr };
-        applyMulticastToInterface4(inaddr);
+        applyMulticastToInterface4(ifitem->index);
     }
 }
 
@@ -840,31 +1209,28 @@ static void sendData(int fd, const CAEndpoint_t *endpoint,
     }
 
     char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
-    (void)secure;   // eliminates release warning
+
+    (void)cast;  // eliminates release warning
+    (void)fam;
+
     struct sockaddr_storage sock;
     CAConvertNameToAddr(endpoint->addr, endpoint->port, &sock);
 
     socklen_t socklen;
     if (sock.ss_family == AF_INET6)
     {
-        struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sock;
-        if (!sock6->sin6_scope_id)
-        {
-            sock6->sin6_scope_id = endpoint->interface;
-        }
+        /** @todo figure out correct usage for ifindex, and sin6_scope_id */
         socklen = sizeof(struct sockaddr_in6);
     }
     else
     {
         socklen = sizeof(struct sockaddr_in);
     }
-
+#if !defined(_WIN32)
     ssize_t len = sendto(fd, data, dlen, 0, (struct sockaddr *)&sock, socklen);
-    if (-1 == len)
+    if (OC_SOCKET_ERROR == len)
     {
          // If logging is not defined/enabled.
-        (void)cast;
-        (void)fam;
         if (g_ipErrorHandler)
         {
             g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
@@ -875,6 +1241,45 @@ static void sendData(int fd, const CAEndpoint_t *endpoint,
     {
         OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %zd bytes", secure, cast, fam, len);
     }
+#else
+    int err = 0;
+    int len = 0;
+    int sent = 0;
+    do {
+        len = sendto(fd, ((char*)data) + sent, dlen - sent, 0, (struct sockaddr *)&sock, socklen);
+        if (OC_SOCKET_ERROR == len)
+        {
+            err = WSAGetLastError();
+            if ((WSAEWOULDBLOCK != err) && (WSAENOBUFS != err))
+            {
+                 // If logging is not defined/enabled.
+                if (g_ipErrorHandler)
+                {
+                    g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
+                }
+
+                OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %i", secure, cast, fam, err);
+            }
+        }
+        else
+        {
+            sent += len;
+            if (sent != len)
+            {
+                OIC_LOG_V(DEBUG, TAG, "%s%s %s sendTo (Partial Send) is successful: "
+                                      "currently sent: %ld bytes, "
+                                      "total sent: %ld bytes, "
+                                      "remaining: %ld bytes",
+                                      secure, cast, fam, len, sent, dlen-sent);
+            }
+            else
+            {
+                OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %ld bytes",
+                                     secure, cast, fam, len);
+            }
+        }
+    } while ((OC_SOCKET_ERROR == len) && ((WSAEWOULDBLOCK == err) || (WSAENOBUFS == err)) || (sent < dlen));
+#endif
 }
 
 static void sendMulticastData6(const u_arraylist_t *iflist,
@@ -905,7 +1310,7 @@ static void sendMulticastData6(const u_arraylist_t *iflist,
         {
             continue;
         }
-        if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
+        if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
         {
             continue;
         }
@@ -915,9 +1320,9 @@ static void sendMulticastData6(const u_arraylist_t *iflist,
         }
 
         int index = ifitem->index;
-        if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &index, sizeof (index)))
+        if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, OPTVAL_T(&index), sizeof (index)))
         {
-            OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", strerror(errno));
+            OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", CAIPS_GET_ERROR);
             return;
         }
         sendData(fd, endpoint, data, datalen, "multicast", "ipv6");
@@ -930,8 +1335,15 @@ static void sendMulticastData4(const u_arraylist_t *iflist,
 {
     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
 
+#if defined(USE_IP_MREQN)
     struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
-                             .imr_ifindex = 0 };
+                             .imr_address.s_addr = htonl(INADDR_ANY),
+                             .imr_ifindex = 0};
+#else
+    struct ip_mreq mreq  = { .imr_multiaddr = IPv4MulticastAddress,
+                             .imr_interface = {0}};
+#endif
+
     OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
     int fd = caglobals.ip.u4.fd;
 
@@ -943,7 +1355,7 @@ static void sendMulticastData4(const u_arraylist_t *iflist,
         {
             continue;
         }
-        if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
+        if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
         {
             continue;
         }
@@ -951,14 +1363,15 @@ static void sendMulticastData4(const u_arraylist_t *iflist,
         {
             continue;
         }
-
-        struct in_addr inaddr;
-        inaddr.s_addr = ifitem->ipv4addr;
-        mreq.imr_address = inaddr;
-        if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof (mreq)))
+#if defined(USE_IP_MREQN)
+        mreq.imr_ifindex = ifitem->index;
+#else
+        mreq.imr_interface.s_addr = htonl(ifitem->index);
+#endif
+        if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, OPTVAL_T(&mreq), sizeof (mreq)))
         {
             OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
-                    strerror(errno));
+                    CAIPS_GET_ERROR);
         }
         sendData(fd, endpoint, data, datalen, "multicast", "ipv4");
     }
@@ -1001,7 +1414,7 @@ void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
             endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
         }
 
-        int fd;
+        CASocketFd_t fd;
         if (caglobals.ip.ipv6enabled && (endpoint->flags & CA_IPV6))
         {
             fd = isSecure ? caglobals.ip.u6s.fd : caglobals.ip.u6.fd;
@@ -1058,7 +1471,7 @@ CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
         }
 
         eps[j].adapter = CA_ADAPTER_IP;
-        eps[j].interface = 0;
+        eps[j].ifindex = 0;
 
         if (ifitem->family == AF_INET6)
         {
@@ -1069,15 +1482,16 @@ CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
         {
             eps[j].flags = CA_IPV4;
             eps[j].port = caglobals.ip.u4.port;
-
-            inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
+            /** @todo eps[j].addr not populated with IPv4 address string.
+             * it was using ifitem->ipv4addr to accomplish this.
+             * Need to understand what ipv4addr means to whom*/
         }
 
 #ifdef __WITH_DTLS__
         j++;
 
         eps[j].adapter = CA_ADAPTER_IP;
-        eps[j].interface = 0;
+        eps[j].ifindex = 0;
 
         if (ifitem->family == AF_INET6)
         {
index a2f2e4f..cf1a771 100644 (file)
@@ -89,6 +89,7 @@ static CAResult_t CAIPInitializeNetworkMonitorList()
             return CA_STATUS_FAILED;
         }
     }
+    return CA_STATUS_OK;
 }
 
 static void CAIPDestroyNetworkMonitorList()
@@ -158,7 +159,7 @@ static void CARemoveNetworkMonitorList(int ifiindex)
     {
         CAInterface_t *removedifitem = (CAInterface_t *) u_arraylist_get(
                 g_netInterfaceList, list_index);
-        if (removedifitem && removedifitem->index == ifiindex)
+        if (removedifitem && ((int)removedifitem->index) == ifiindex)
         {
             if (u_arraylist_remove(g_netInterfaceList, list_index))
             {
diff --git a/resource/csdk/connectivity/src/ip_adapter/windows/SConscript b/resource/csdk/connectivity/src/ip_adapter/windows/SConscript
new file mode 100644 (file)
index 0000000..f10999f
--- /dev/null
@@ -0,0 +1,12 @@
+#######################################################
+#       Build IP adapter for MSYS2
+#######################################################
+
+Import('env', 'src_dir')
+import os.path
+target_os = env.get('TARGET_OS')
+env.AppendUnique(CPPPATH = [ os.path.join(src_dir, target_os) ])
+
+src_files = [ 'caipnwmonitor.c' ]
+
+Return('src_files')
diff --git a/resource/csdk/connectivity/src/ip_adapter/windows/caipnwmonitor.c b/resource/csdk/connectivity/src/ip_adapter/windows/caipnwmonitor.c
new file mode 100644 (file)
index 0000000..7d3088f
--- /dev/null
@@ -0,0 +1,288 @@
+/* *****************************************************************
+*
+* 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.
+*
+******************************************************************/
+
+#include "caipinterface.h"
+
+#include <sys/types.h>
+#include <string.h>
+#include <errno.h>
+#include <winsock2.h>
+#include <iphlpapi.h>
+#include "platform_features.h"
+#include <iptypes.h>
+#include <stdbool.h>
+#include "caadapterutils.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+
+#define TAG "IP_MONITOR"
+
+/**
+ * @todo Implement network interface monitoring in case the IP changes.
+ * Not critical for win32 bring-up.
+ */
+CAResult_t CAIPStartNetworkMonitor()
+{
+    return CA_STATUS_OK;
+}
+
+/**
+ * @todo Implement network interface monitoring in case the IP changes.
+ * Not critical for win32 bring-up.
+ */
+CAResult_t CAIPStopNetworkMonitor()
+{
+    return CA_STATUS_OK;
+}
+
+/**
+ * @todo Implement network interface monitoring.
+ * Not used in win32, but caipserver currently requires this function
+ * be defined. not critical.
+ */
+int CAGetPollingInterval(int interval)
+{
+    return interval;
+}
+
+/**
+ * @todo Implement network interface monitoring.
+ * Not used in win32, but caipserver currently requires this function
+ * be defined. not critical.
+ */
+CAInterface_t *CAFindInterfaceChange()
+{
+    CAInterface_t *foundNewInterface = NULL;
+    return foundNewInterface;
+}
+
+/**
+ * @todo Implement network interface monitoring.
+ * Not critical for win32 bring-up.
+ */
+void CAIPSetNetworkMonitorCallback(CAIPConnectionStateChangeCallback callback)
+{
+    return;
+}
+
+bool IsValidAdapter(PIP_ADAPTER_ADDRESSES pAdapterAddr, int desiredIndex, uint16_t family)
+{
+    bool valid = true;
+
+    // If desiredIndex is non-zero, then only retrieve adapter corresponding to desiredIndex.
+    // If desiredIndex is zero, then retrieve all adapters.
+    if (desiredIndex && (pAdapterAddr->IfIndex != desiredIndex))
+    {
+        OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i not interesting.", pAdapterAddr->IfIndex);
+        valid = false;
+    }
+
+    if (pAdapterAddr->IfType & IF_TYPE_SOFTWARE_LOOPBACK)
+    {
+        OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i is loopback.", pAdapterAddr->IfIndex);
+        valid = false;
+    }
+
+    // If the adapter must support the requested family
+    if ((family == AF_INET6) && ((pAdapterAddr->Flags & IP_ADAPTER_IPV6_ENABLED) == 0))
+    {
+        OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i does not support IPv6", pAdapterAddr->IfIndex);
+        valid = false;
+    }
+    else if ((family == AF_INET) && ((pAdapterAddr->Flags & IP_ADAPTER_IPV4_ENABLED) == 0))
+    {
+        OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i does not support IPv4", pAdapterAddr->IfIndex);
+        valid = false;
+    }
+
+    if ((pAdapterAddr->OperStatus & IfOperStatusUp) == 0)
+    {
+        OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i is not operational.", pAdapterAddr->IfIndex);
+        valid = false;
+    }
+    return valid;
+
+}
+
+
+bool AddCAInterface(u_arraylist_t *iflist, const char * name, uint32_t index, uint16_t family)
+{
+    bool bSucceeded = false;
+    CAInterface_t *ifitem = (CAInterface_t *)OICCalloc(1, sizeof(*ifitem));
+    if (ifitem)
+    {
+        OICStrcpy(ifitem->name, INTERFACE_NAME_MAX, name);
+        ifitem->index = index;
+        ifitem->family = family;
+        ifitem->flags |= IFF_UP;// IsValidAddress() will have filtered out non-operational addresses already.
+
+        if (u_arraylist_add(iflist, ifitem))
+        {
+            bSucceeded = true;
+        }
+        else
+        {
+            OIC_LOG(ERROR, TAG, "u_arraylist_add failed");
+            OICFree(ifitem);
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "Allocating memory for a CAInterface_t failed");
+    }
+    return bSucceeded;
+}
+
+bool AddInterfaces(PIP_ADAPTER_ADDRESSES pAdapterAddr, u_arraylist_t *iflist, int desiredIndex)
+{
+    bool bSucceeded = false;
+    for (PIP_ADAPTER_ADDRESSES pCurAdapterAddr = pAdapterAddr;
+         pCurAdapterAddr != NULL; pCurAdapterAddr = pCurAdapterAddr->Next)
+    {
+        OIC_LOG_V(DEBUG, TAG, "\tInterface Index: %u", pCurAdapterAddr->IfIndex);
+        OIC_LOG_V(DEBUG, TAG, "\tInterface  name: %s", pCurAdapterAddr->AdapterName);
+
+        // Prefer IPv6 over IPv4.
+        if (pCurAdapterAddr->Flags & IP_ADAPTER_IPV6_ENABLED)
+        {
+            // Do not add loopback, duplicate, or non-operational adapters
+            if (IsValidAdapter(pCurAdapterAddr, desiredIndex, AF_INET6))
+            {
+                if (AddCAInterface(iflist, pCurAdapterAddr->AdapterName, pCurAdapterAddr->IfIndex, AF_INET6))
+                {
+                    OIC_LOG_V(DEBUG, TAG, "\t\tAdded IPv6 interface %i", pCurAdapterAddr->IfIndex);
+                    bSucceeded = true;
+                }
+                else
+                {
+                    OIC_LOG_V(ERROR, TAG, "\tAdding IPv6 interface %i failed", pCurAdapterAddr->IfIndex);
+                    break;
+                }
+            }
+            else
+            {
+                OIC_LOG_V(DEBUG, TAG, "\t\tIPv6 interface %i not valid, skipping...", pCurAdapterAddr->IfIndex);
+            }
+        }
+        else if (pCurAdapterAddr->Flags & IP_ADAPTER_IPV4_ENABLED)
+        {
+            // Do not add loopback, duplicate, or non-operational adapters
+            if (IsValidAdapter(pCurAdapterAddr, desiredIndex, AF_INET))
+            {
+                if (AddCAInterface(iflist, pCurAdapterAddr->AdapterName, pCurAdapterAddr->IfIndex, AF_INET))
+                {
+                    OIC_LOG_V(DEBUG, TAG, "\t\tAdded IPv4 interface %i", pCurAdapterAddr->IfIndex);
+                    bSucceeded = true;
+                }
+                else
+                {
+                    OIC_LOG_V(ERROR, TAG, "\tAdding IPv4 interface %i failed", pCurAdapterAddr->IfIndex);
+                    break;
+                }
+            }
+            else
+            {
+                OIC_LOG_V(DEBUG, TAG, "\t\tIPv6 interface %i not valid, skipping...", pCurAdapterAddr->IfIndex);
+            }
+
+        }
+    }
+    return bSucceeded;
+}
+
+PIP_ADAPTER_ADDRESSES GetAdapters()
+{
+    ULONG ulOutBufLen = sizeof(IP_ADAPTER_ADDRESSES);
+    PIP_ADAPTER_ADDRESSES pAdapterAddr = (IP_ADAPTER_ADDRESSES *) OICMalloc(ulOutBufLen);
+    if (pAdapterAddr != NULL)
+    {
+        ULONG flags = 0;
+        ULONG ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAdapterAddr, &ulOutBufLen);
+        if (ERROR_BUFFER_OVERFLOW == ret)
+        {
+            // Redo with updated length
+            OICFree(pAdapterAddr);
+            pAdapterAddr = (PIP_ADAPTER_ADDRESSES) OICMalloc(ulOutBufLen);
+            if (pAdapterAddr != NULL) {
+                ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAdapterAddr, &ulOutBufLen);
+                if (NO_ERROR != ret)
+                {
+                    OIC_LOG(ERROR, TAG, "GetAdaptersAddresses() failed");
+                    OICFree(pAdapterAddr);
+                    pAdapterAddr = NULL;
+                }
+                else
+                {
+                    // Succeeded getting adapters
+                }
+            }
+            else
+            {
+                OIC_LOG(ERROR, TAG, "Second time allocating memory for GetAdaptersAddresses() failed");
+            }
+        }
+        else
+        {
+            OIC_LOG(ERROR, TAG, "Expected GetAdaptersAddresses() to fail on first try, but it didn't.");
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "First time allocating memory for GetAdaptersAddresses() failed");
+    }
+    return pAdapterAddr;
+}
+
+u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
+{
+    u_arraylist_t *iflist = u_arraylist_create();
+    if (iflist)
+    {
+        PIP_ADAPTER_ADDRESSES pAdapterAddr = NULL;
+        pAdapterAddr = GetAdapters();
+        if (pAdapterAddr)
+        {
+            // Cycle through adapters
+            // Add valid adapters to the interface list.
+            bool ret = AddInterfaces(pAdapterAddr, iflist, desiredIndex);
+            if (false == ret)
+            {
+                OIC_LOG(ERROR, TAG, "AddInterfaces() failed");
+                u_arraylist_destroy(iflist);
+                iflist = NULL;
+            }
+
+            // Finished with Adapter List
+            OICFree(pAdapterAddr);
+        }
+        else
+        {
+            OIC_LOG(ERROR, TAG, "Enumerating Adapters failed");
+            u_arraylist_destroy(iflist);
+            iflist = NULL;
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "Failed to create iflist");
+    }
+    return iflist;
+}
index 9247bc3..0b06a1d 100644 (file)
@@ -133,7 +133,7 @@ CAResult_t CANfcCreateJniInterfaceObject()
     VERIFY_NON_NULL(g_jvm, TAG, "g_jvm");\r
 \r
     bool isAttached = false;\r
-    JNIEnv* env;\r
+    JNIEnv* env = NULL;\r
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);\r
     if (JNI_OK != res)\r
     {\r
@@ -243,7 +243,7 @@ CAResult_t CANFCStartServer()
 \r
     OIC_LOG(INFO, TAG, "CANFCStartServer : IN");\r
 \r
-    JNIEnv* env;\r
+    JNIEnv* env = NULL;\r
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);\r
     if (JNI_OK != res)\r
     {\r
@@ -531,7 +531,7 @@ CAResult_t CANfcSendDataImpl(const CAEndpoint_t * ep, const char* data, uint32_t
 \r
     OIC_LOG(INFO, TAG, "CANfcSendDataImpl moved env outside");\r
     bool isAttached = false;\r
-    JNIEnv* env;\r
+    JNIEnv* env = NULL;\r
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);\r
     if (JNI_OK != res)\r
     {\r
index d2fda2c..d81f600 100644 (file)
@@ -175,22 +175,18 @@ void CATCPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
     }
 }
 
-static void CATCPConnectionHandler(const char *addr, uint16_t port, bool isConnected)
+static void CATCPConnectionHandler(const CAEndpoint_t *endpoint, bool isConnected)
 {
-    CAEndpoint_t endpoint = { .adapter =  CA_ADAPTER_TCP,
-                              .port = port };
-    OICStrcpy(endpoint.addr, sizeof(endpoint.addr), addr);
-
     // Pass the changed connection status to RI Layer for keepalive.
     if (g_connKeepAliveCallback)
     {
-        g_connKeepAliveCallback(&endpoint, isConnected);
+        g_connKeepAliveCallback(endpoint, isConnected);
     }
 
     // Pass the changed connection status to CAUtil.
     if (g_connectionChangeCallback)
     {
-        g_connectionChangeCallback(&endpoint, isConnected);
+        g_connectionChangeCallback(endpoint, isConnected);
     }
 }
 
@@ -202,9 +198,7 @@ void CATCPSetKeepAliveCallbacks(CAKeepAliveConnectionCallback ConnHandler)
 static void CAInitializeTCPGlobals()
 {
     caglobals.tcp.ipv4.fd = -1;
-    caglobals.tcp.ipv4.port = 0;
     caglobals.tcp.ipv6.fd = -1;
-    caglobals.tcp.ipv6.port = 0;
     caglobals.tcp.selectTimeout = CA_TCP_SELECT_TIMEOUT;
     caglobals.tcp.listenBacklog = CA_TCP_LISTEN_BACKLOG;
     caglobals.tcp.svrlist = NULL;
@@ -274,6 +268,10 @@ CAResult_t CAStartTCP()
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
+    // Specific the port number received from application.
+    caglobals.tcp.ipv4.port = caglobals.ports.tcp.u4;
+    caglobals.tcp.ipv6.port = caglobals.ports.tcp.u6;
+
 #ifndef SINGLE_THREAD
     if (CA_STATUS_OK != CATCPInitializeQueueHandles())
     {
index 87116e1..bef9fab 100644 (file)
@@ -92,7 +92,7 @@ static void CATCPDestroyCond();
 static int CACreateAcceptSocket(int family, CASocket_t *sock);
 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
 static void CAFindReadyMessage();
-static void CASelectReturned(fd_set *readFds, int ret);
+static void CASelectReturned(fd_set *readFds);
 static void CAReceiveMessage(int fd);
 static void CAReceiveHandler(void *data);
 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo);
@@ -216,10 +216,10 @@ static void CAFindReadyMessage()
         return;
     }
 
-    CASelectReturned(&readFds, ret);
+    CASelectReturned(&readFds);
 }
 
-static void CASelectReturned(fd_set *readFds, int ret)
+static void CASelectReturned(fd_set *readFds)
 {
     VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
 
@@ -483,7 +483,7 @@ static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
         if (!sock6->sin6_scope_id)
         {
-            sock6->sin6_scope_id = svritem->sep.endpoint.interface;
+            sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
         }
         socklen = sizeof(struct sockaddr_in6);
     }
@@ -615,6 +615,15 @@ static void CAInitializePipe(int *fds)
     }
 }
 
+#define NEWSOCKET(FAMILY, NAME) \
+    caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
+    if (caglobals.tcp.NAME.fd == -1) \
+    { \
+        caglobals.tcp.NAME.port = 0; \
+        caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
+    } \
+    CHECKFD(caglobals.tcp.NAME.fd);
+
 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
 {
     if (caglobals.tcp.started)
@@ -651,11 +660,8 @@ CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
 
     if (caglobals.server)
     {
-        caglobals.tcp.ipv4.fd = CACreateAcceptSocket(AF_INET, &caglobals.tcp.ipv4);
-        CHECKFD(caglobals.tcp.ipv4.fd);
-        caglobals.tcp.ipv6.fd = CACreateAcceptSocket(AF_INET6, &caglobals.tcp.ipv6);
-        CHECKFD(caglobals.tcp.ipv6.fd);
-
+        NEWSOCKET(AF_INET, ipv4);
+        NEWSOCKET(AF_INET6, ipv6);
         OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
                   caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
         OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
@@ -884,9 +890,10 @@ CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
         return NULL;
     }
     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
+    svritem->sep.endpoint.adapter = endpoint->adapter;
     svritem->sep.endpoint.port = endpoint->port;
     svritem->sep.endpoint.flags = endpoint->flags;
-    svritem->sep.endpoint.interface = endpoint->interface;
+    svritem->sep.endpoint.ifindex = endpoint->ifindex;
 
     // #2. create the socket and connect to TCP server
     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
@@ -919,7 +926,7 @@ CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
     // pass the connection information to CA Common Layer.
     if (g_connectionCallback)
     {
-        g_connectionCallback(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, true);
+        g_connectionCallback(&(svritem->sep.endpoint), true);
     }
 
     return svritem;
@@ -942,7 +949,7 @@ CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
     // pass the connection information to CA Common Layer.
     if (g_connectionCallback)
     {
-        g_connectionCallback(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, false);
+        g_connectionCallback(&(svritem->sep.endpoint), false);
     }
 
     OICFree(svritem);
index 688a04f..f4a6b3e 100644 (file)
@@ -29,7 +29,6 @@ src_dir = catest_env.get('SRC_DIR')
 # Build flags
 ######################################################################
 catest_env.PrependUnique(CPPPATH = [
-                '../../ocsocket/include',
                 '../../logger/include',
                 '../../stack/include',
                 '../../extlibs/cjson',
@@ -43,11 +42,9 @@ if '-lpthread' in tmplist:
     catest_env.Replace(LINKFLAGS = tmplist)
 
 catest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
-catest_env.AppendUnique(LIBS = ['pthread'])
 catest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 catest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs'])
-catest_env.PrependUnique(LIBS = ['m',
-                                    'octbstack',
+catest_env.PrependUnique(LIBS = ['octbstack',
                                     'connectivity_abstraction',
                                     'coap',
                                     'gtest',
@@ -55,15 +52,27 @@ catest_env.PrependUnique(LIBS = ['m',
 
 target_os = env.get('TARGET_OS')
 
-if target_os not in ['arduino', 'darwin', 'ios']:
+if target_os not in ['arduino', 'darwin', 'ios', 'msys_nt', 'windows']:
        catest_env.AppendUnique(LIBS=['rt'])
 
 if env.get('SECURED') == '1':
-    catest_env.AppendUnique(LIBS = ['tinydtls'])
+       catest_env.AppendUnique(LIBS = ['tinydtls'])
+       catest_env.AppendUnique(LIBS = ['timer'])
+
+if env.get('WITH_RD') == '1':
+       catest_env.PrependUnique(LIBS = ['resource_directory'])
 
 if 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'])
+else:
+       catest_env.PrependUnique(LIBS = ['m', 'pthread'])
+
 ######################################################################
 # Source files and Targets
 ######################################################################
@@ -92,7 +101,8 @@ Alias("test", [catests])
 
 env.AppendTarget('test')
 if env.get('TEST') == '1':
-        if target_os == 'linux':
+        if target_os in ['linux', 'windows']:
+                catest_env.AppendENVPath('PATH', env.get('BUILD_DIR'))
                 from tools.scons.RunTest import *
                 run_test(catest_env,
                          'resource_csdk_connectivity_test.memcheck',
index d413bb1..e8c1986 100644 (file)
@@ -18,6 +18,7 @@
  *
  ******************************************************************/
 
+#include "platform_features.h"
 #include "gtest/gtest.h"
 #include "cainterface.h"
 #include "cautilinterface.h"
@@ -159,12 +160,6 @@ int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
 }
 #endif  //__WITH_DTLS__
 
-int main(int argc, char **argv)
-{
-    testing::InitGoogleTest(&argc, argv);
-    return RUN_ALL_TESTS();
-}
-
 // CAInitialize TC
 // check return value
 TEST(InitializeTest, TC_01_Positive_01)
index d43c6f5..09e7550 100644 (file)
@@ -29,7 +29,8 @@
 
 class CABlockTransferTests : public testing::Test {
     protected:
-    virtual void SetUp() {
+    virtual void SetUp()
+    {
         CAInitialize();
     }
 
index 1c3f34e..54d9fb8 100644 (file)
 #include <camutex.h>
 #include <cathreadpool.h>
 
+#ifdef HAVE_TIME_H
 #include <time.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
+#endif
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#include "platform_features.h"
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+
+#define HNS_PER_US 10
 
 //#define DEBUG_VERBOSE 1
 
@@ -68,6 +80,18 @@ uint64_t getAbsTime()
     struct timespec ts;
     clock_gettime(CLOCK_MONOTONIC, &ts);
     currentTime = ts.tv_sec * USECS_PER_SEC + ts.tv_nsec / 1000;
+#elif defined(_WIN32)
+    FILETIME time;
+    ULARGE_INTEGER microseconds;
+
+    GetSystemTimeAsFileTime(&time);
+
+    // Time is in hundreds of nanoseconds, so we must convert to uS
+    microseconds.LowPart = time.dwLowDateTime;
+    microseconds.HighPart = time.dwHighDateTime;
+    microseconds.QuadPart /= HNS_PER_US;
+
+    currentTime = microseconds.QuadPart;
 #else
     struct timeval tv;
     gettimeofday(&tv, NULL);
@@ -209,7 +233,12 @@ void condFunc(void *context)
     DBG_printf("Thread_%d: completed.\n", pData->id);
 }
 
+#ifdef _WIN32
+/** @todo: Enable.  Need to solve nanosleep issue */
+TEST(ConditionTests, DISABLED_TC_02_SIGNAL)
+#else
 TEST(ConditionTests, TC_02_SIGNAL)
+#endif
 {
     const int MAX_WAIT_MS = 2000;
     ca_thread_pool_t mythreadpool;
@@ -372,7 +401,12 @@ TEST(ConditionTests, TC_03_BROADCAST)
     ca_thread_pool_free(mythreadpool);
 }
 
-TEST(CondTests, TC_04_TIMECHECK)
+#ifdef _WIN32
+/** @todo: Enable.  Need to solve nanosleep issue */
+TEST(ConditionTests, DISABLED_TC_04_TIMECHECK)
+#else
+TEST(ConditionTests, TC_04_TIMECHECK)
+#endif
 {
     uint64_t begin = getAbsTime();
 
@@ -518,7 +552,14 @@ TEST(ConditionTests, TC_07_WAITDURATION)
 
     double secondsDiff = (end - beg) / (double) USECS_PER_SEC;
 
+#ifdef _WIN32
+    // Windows does not guarantee that the thread will resume execution from a
+    // yield within any given time frame. We will assume that the threads
+    // should have resumed within one second of the requested timeout value.
+    EXPECT_NEAR(TARGET_WAIT, secondsDiff, 1.00);
+#else
     EXPECT_NEAR(TARGET_WAIT, secondsDiff, 0.05);
+#endif
 
     ca_mutex_unlock(sharedMutex);
 
index b07eb6f..c701a2e 100644 (file)
@@ -20,6 +20,7 @@
 
 #include "gtest/gtest.h"
 
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
 
 /**
@@ -41,6 +42,12 @@ void workaroundHook()
         pthread_key_delete(key);
     }
 }
+#else
+void workaroundHook()
+{
+    return;
+};
+#endif
 
 
 TEST(BaseTest, WorldIsSane)
index fa3cb81..c15b05c 100644 (file)
@@ -66,6 +66,14 @@ CAResult_t CAManagerLEClientInitialize(JNIEnv *env, JavaVM *jvm, jobject context
  * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
  */
 CAResult_t CAManagerLEClientTerminate(JNIEnv *env);
+
+/**
+ * set BLE scan interval time and working count.
+ * @param[in]  intervalTime         interval time(Seconds).
+ * @param[in]  workingCount         working count for selected interval time.
+ */
+void CAManagerLESetScanInterval(jint intervalTime, jint workingCount);
+
 #endif
 
 #ifdef __cplusplus
index b982b74..0d24bad 100644 (file)
@@ -46,7 +46,7 @@ static const char CLASSPATH_BT_DEVICE[] = "android/bluetooth/BluetoothDevice";
 
 static void CABTPaitingCreateJNIInterfaceObject(jobject context)
 {
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     OIC_LOG(INFO, TAG, "OICEDRCreateJNIInterfaceObject");
 
     if ((*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
index fb5742b..c77ea8f 100644 (file)
@@ -50,7 +50,7 @@ CAResult_t CASetLEClientAutoConnectionDeviceInfo(const char* address)
     VERIFY_NON_NULL(address, TAG, "address");
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -126,7 +126,7 @@ CAResult_t CAUnsetLEClientAutoConnectionDeviceInfo(const char* address)
     VERIFY_NON_NULL(address, TAG, "address");
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -280,6 +280,12 @@ CAResult_t CAManagerLEClientTerminate(JNIEnv *env)
     return res;
 }
 
+void CAManagerLESetScanInterval(jint interval, jint count)
+{
+    OIC_LOG(DEBUG, TAG, "CAManagerLESetScanInterval");
+    CALERestartScanWithInterval(interval, count);
+}
+
 JNIEXPORT void JNICALL
 Java_org_iotivity_ca_CaLeClientInterface_caManagerAdapterStateChangedCallback(
         JNIEnv *env, jobject obj, jint state)
index 046ace4..cdf46d7 100644 (file)
@@ -53,7 +53,7 @@ static void CAManagerAdapterMonitorHandler(CATransportAdapter_t adapter,
 
 static void CAManagerConnectionMonitorHandler(const CAEndpoint_t *info, bool isConnected)
 {
-    if (!info || !info->addr)
+    if (!info || !info->addr[0])
     {
         OIC_LOG(ERROR, TAG, "remoteAddress is NULL");
         return;
@@ -114,6 +114,104 @@ CAResult_t CAUnsetAutoConnectionDeviceInfo(const char *address)
 #endif
 }
 
+CAResult_t CASetPortNumberToAssign(CATransportAdapter_t adapter,
+                                   CATransportFlags_t flag, uint16_t port)
+{
+    uint16_t *targetPort = 0;
+
+    if (CA_ADAPTER_IP & adapter)
+    {
+        if (CA_SECURE & flag)
+        {
+            if (CA_IPV6 & flag)
+            {
+                targetPort = &caglobals.ports.udp.u6s;
+            }
+            else if (CA_IPV4 & flag)
+            {
+                targetPort = &caglobals.ports.udp.u4s;
+            }
+        }
+        else
+        {
+            if (CA_IPV6 & flag)
+            {
+                targetPort = &caglobals.ports.udp.u6;
+            }
+            else if (CA_IPV4 & flag)
+            {
+                targetPort = &caglobals.ports.udp.u4;
+            }
+        }
+    }
+#ifdef TCP_ADAPTER
+    if (CA_ADAPTER_TCP & adapter)
+    {
+        if (CA_IPV6 & flag)
+        {
+            targetPort = &caglobals.ports.tcp.u6;
+        }
+        else if (CA_IPV4 & flag)
+        {
+            targetPort = &caglobals.ports.tcp.u4;
+        }
+    }
+#endif
+
+    if (targetPort)
+    {
+        *targetPort = port;
+        return CA_STATUS_OK;
+    }
+
+    return CA_NOT_SUPPORTED;
+}
+
+uint16_t CAGetAssignedPortNumber(CATransportAdapter_t adapter, CATransportFlags_t flag)
+{
+    OIC_LOG(DEBUG, TAG, "CAGetAssignedPortNumber");
+
+    if (CA_ADAPTER_IP & adapter)
+    {
+        if (CA_SECURE & flag)
+        {
+            if (CA_IPV6 & flag)
+            {
+                return caglobals.ip.u6s.port;
+            }
+            else if (CA_IPV4 & flag)
+            {
+                return caglobals.ip.u4s.port;
+            }
+        }
+        else
+        {
+            if (CA_IPV6 & flag)
+            {
+                return caglobals.ip.u6.port;
+            }
+            else if (CA_IPV4 & flag)
+            {
+                return caglobals.ip.u4.port;
+            }
+        }
+    }
+#ifdef TCP_ADAPTER
+    if (CA_ADAPTER_TCP & adapter)
+    {
+        if (CA_IPV6 & flag)
+        {
+            return caglobals.tcp.ipv6.port;
+        }
+        else if (CA_IPV4 & flag)
+        {
+            return caglobals.tcp.ipv4.port;
+        }
+    }
+#endif
+    return 0;
+}
+
 #ifdef __ANDROID__
 /**
  * initialize client connection manager
@@ -203,4 +301,16 @@ void CAUtilSetFoundDeviceListener(jobject listener)
     (void)listener;
 #endif
 }
+
+CAResult_t CAUtilSetLEScanInterval(jint intervalTime, jint workingCount)
+{
+    OIC_LOG(DEBUG, TAG, "CAUtilSetLEScanInterval");
+#ifdef LE_ADAPTER
+    CAManagerLESetScanInterval(intervalTime, workingCount);
+    return CA_STATUS_OK;
+#else
+    OIC_LOG(DEBUG, TAG, "it is not supported");
+    return CA_NOT_SUPPORTED;
+#endif
+}
 #endif
index 40c60bb..b81fb7e 100644 (file)
@@ -1,13 +1,16 @@
 Import('env')
 import os
 
-env.AppendUnique(CPPPATH = [os.path.join(Dir('.').abspath, './include')])
+env.AppendUnique(CPPPATH = [os.path.join(Dir('.').abspath, 'include'),
+                            '../../c_common'
+    ])
+
 if env.get('TARGET_OS') in ['arduino']:
        env.AppendUnique(CPPPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/c_common/oic_string/include')])
 if env.get('TARGET_OS') == 'tizen':
        env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 else:
-       env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/csdk/logger/')])
+       env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk', 'logger')])
 
 env.PrependUnique(LIBS = ['logger'])
 
index 932221d..0b42ead 100644 (file)
@@ -21,7 +21,7 @@
 #ifndef LOGGER_H_
 #define LOGGER_H_
 
-#define IOTIVITY_VERSION "1.1.0"
+#define IOTIVITY_VERSION "1.1.1"
 
 #include <stdint.h>
 #include <stdio.h>
@@ -67,6 +67,12 @@ typedef enum {
     FATAL = DLOG_ERROR
 } LogLevel;
 #else
+
+/** @todo temporary work-around until better names with prefixes are used for the enum values. */
+#ifdef ERROR
+#undef ERROR
+#endif
+
 typedef enum {
     DEBUG = 0,
     INFO,
@@ -89,7 +95,7 @@ void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint1
 
 #define OCLog(level,tag,mes) LOG_(LOG_ID_MAIN, (level), (tag), mes)
 #define OCLogv(level,tag,fmt,args...) LOG_(LOG_ID_MAIN, (level),tag,fmt,##args)
-#elif defined(ANDROID) || defined(__linux__) || defined(__APPLE__)
+#elif !defined(ARDUINO)
     /**
      * Configure logger to use a context that defines a custom logger function
      *
@@ -196,7 +202,7 @@ void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint1
 #define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)\
     OCLogBuffer((level), (tag), (buffer), (bufferSize))
 
-#else // These macros are defined for Linux, Android, and Arduino
+#else // These macros are defined for Linux, Android, Win32, and Arduino
 
 #define OIC_LOG_INIT()    OCLogInit()
 
@@ -217,7 +223,7 @@ void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint1
 #define OIC_LOG_CONFIG(ctx)    OCLogConfig((ctx))
 #define OIC_LOG_SHUTDOWN()     OCLogShutdown()
 #define OIC_LOG(level, tag, logStr)  OCLog((level), (tag), (logStr))
-// Define variable argument log function for Linux and Android
+// Define variable argument log function for Linux, Android, and Win32
 #define OIC_LOG_V(level, tag, ...)  OCLogv((level), (tag), __VA_ARGS__)
 
 #endif //ARDUINO
index cc30d58..7a32b46 100644 (file)
 #define _POSIX_C_SOURCE 200809L
 #endif
 
-// Platform check can be extended to check and/or define more, or could be
-// moved into a config.h
-#if !defined(__ARDUINO__) && !defined(ARDUINO)
-#define HAVE_UNISTD_H 1
-#endif
-
 // Pull in _POSIX_TIMERS feature test macro to check for
 // clock_gettime() support.
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
-
-// if we have unistd.h, we're a Unix system
+#endif
 #include <time.h>
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
 
 #include "logger.h"
 #include "string.h"
 #include "logger_types.h"
+#include "platform_features.h"
 
 #ifndef __TIZEN__
 static oc_log_ctx_t *logCtx = 0;
 #endif
+
+#if defined(_MSC_VER)
+#define LINE_BUFFER_SIZE (16 * 2) + 16 + 1  // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
+#else
+static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1;  // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
+#endif //defined(_MSC_VER)
+
 #ifdef __ANDROID__
-#elif defined __linux__ || defined __APPLE__
+#elif defined __linux__ || defined __APPLE__ || defined _WIN32
 static oc_log_level LEVEL_XTABLE[] = {OC_LOG_DEBUG, OC_LOG_INFO,
                                       OC_LOG_WARNING, OC_LOG_ERROR, OC_LOG_FATAL};
 #endif
 
-// Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
-static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1;
-
 // Convert LogLevel to platform-specific severity level.  Store in PROGMEM on Arduino
 #ifdef __ANDROID__
 #ifdef ADB_SHELL
@@ -72,9 +74,10 @@ static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1;
     static android_LogPriority LEVEL[] =
     {ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL};
 #endif
-#elif defined (__linux__) || defined (__APPLE__)
-    static const char *LEVEL[] __attribute__ ((unused)) =
-    {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+#elif defined(__linux__) || defined(__APPLE__) || defined(__msys_nt__)
+    static const char * LEVEL[] __attribute__ ((unused)) = {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+#elif defined(_MSC_VER)
+    static const char * LEVEL[] = {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
 #elif defined ARDUINO
 #include <stdarg.h>
 #include "Arduino.h"
@@ -98,7 +101,10 @@ static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1;
 #else
     #define GET_PROGMEM_BUFFER(buffer, addr) { buffer[0] = '\0';}
 #endif
-#endif // __ANDROID__
+#else // !defined(__ANDROID__) && !defined(ARDUINO)
+    static const char *LEVEL[] __attribute__ ((unused)) =
+    {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+#endif
 
 #ifndef ARDUINO
 
@@ -155,7 +161,7 @@ void OCLogInit()
 
 void OCLogShutdown()
 {
-#if defined(__linux__) || defined(__APPLE__)
+#if defined(__linux__) || defined(__APPLE__) || defined(_WIN32)
     if (logCtx && logCtx->destroy)
     {
         logCtx->destroy(logCtx);
@@ -176,7 +182,7 @@ void OCLogv(LogLevel level, const char * tag, const char * format, ...)
     if (!format || !tag) {
         return;
     }
-    char buffer[MAX_LOG_V_BUFFER_SIZE] = {};
+    char buffer[MAX_LOG_V_BUFFER_SIZE] = {0};
     va_list args;
     va_start(args, format);
     vsnprintf(buffer, sizeof buffer - 1, format, args);
@@ -207,7 +213,7 @@ void OCLog(LogLevel level, const char * tag, const char * logStr)
        __android_log_write(LEVEL[level], tag, logStr);
    #endif
 
-   #elif defined __linux__ || defined __APPLE__
+   #else
        if (logCtx && logCtx->write_level)
        {
            logCtx->write_level(logCtx, LEVEL_XTABLE[level], logStr);
@@ -230,6 +236,12 @@ void OCLog(LogLevel level, const char * tag, const char * logStr)
                sec = when.tv_sec % 60;
                ms = when.tv_nsec / 1000000;
            }
+   #elif defined(_WIN32)
+           SYSTEMTIME systemTime = {0};
+           GetLocalTime(&systemTime);
+           min = (int)systemTime.wMinute;
+           sec = (int)systemTime.wSecond;
+           ms  = (int)systemTime.wMilliseconds;
    #else
            struct timeval now;
            if (!gettimeofday(&now, NULL))
index cabd07c..d9b8816 100644 (file)
@@ -320,7 +320,8 @@ OCStackResult RMCreateRouteOption(const RMRouteOption_t *optValue, CAHeaderOptio
     OIC_LOG_V(DEBUG, RM_TAG, "createoption dlen %u slen [%u]", dLen, sLen);
 
     unsigned int totalLength = 0;
-    void *tempData = NULL;
+    uint8_t *tempData = NULL;
+
     if (0 == dLen && 0 == sLen)
     {
         OIC_LOG(DEBUG, RM_TAG, "Source and destination is not present");
index ccfcda0..a79ab3e 100644 (file)
@@ -22,6 +22,7 @@
 ##
 
 Import('env')
+import os
 
 lib_env = env.Clone()
 SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env')
@@ -56,28 +57,28 @@ libocsrm_env.PrependUnique(CPPPATH = [
                '../security/provisioning/include'
                ])
 
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows']:
        libocsrm_env.AppendUnique(CPPDEFINES  = ['WITH_POSIX'])
-       libocsrm_env.AppendUnique(CFLAGS = ['-std=c99'])
-       libocsrm_env.AppendUnique(CPPDEFINES = ['HAVE_STRINGS_H'])
-
-if target_os not in ['windows', 'winrt']:
-       libocsrm_env.AppendUnique(CFLAGS = ['-Wall'])
+       libocsrm_env.AppendUnique(CFLAGS = ['-std=c99', '-Wall'])
 
 libocsrm_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-libocsrm_env.AppendUnique(LIBS = ['coap', 'm'])
+libocsrm_env.AppendUnique(LIBS = ['coap'])
 
 if target_os == 'arduino':
        libocsrm_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO'])
-else:
+elif target_os not in ['windows', 'msys_nt']:
        libocsrm_env.AppendUnique(CFLAGS = ['-fPIC'])
+       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')])
 
 if target_os in ['darwin', 'ios']:
        libocsrm_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
        libocsrm_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
        libocsrm_env.AppendUnique(LIBS = ['coap'])
 
-if not env.get('RELEASE'):
+if env.get('LOGGING'):
        libocsrm_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 
 if env.get('DTLS_WITH_X509') == '1':
@@ -87,65 +88,48 @@ if env.get('DTLS_WITH_X509') == '1':
 # Source files and Targets
 ######################################################################
 OCSRM_SRC = 'src/'
+libocsrm_src = [
+       OCSRM_SRC + 'secureresourcemanager.c',
+       OCSRM_SRC + 'resourcemanager.c',
+       OCSRM_SRC + 'aclresource.c',
+       OCSRM_SRC + 'verresource.c',
+       OCSRM_SRC + 'amaclresource.c',
+       OCSRM_SRC + 'amsmgr.c',
+       OCSRM_SRC + 'pstatresource.c',
+       OCSRM_SRC + 'doxmresource.c',
+       OCSRM_SRC + 'credresource.c',
+       OCSRM_SRC + 'svcresource.c',
+       OCSRM_SRC + 'pconfresource.c',
+       OCSRM_SRC + 'dpairingresource.c',
+       OCSRM_SRC + 'policyengine.c',
+       OCSRM_SRC + 'psinterface.c',
+       OCSRM_SRC + 'srmresourcestrings.c',
+       OCSRM_SRC + 'srmutility.c',
+       OCSRM_SRC + 'iotvticalendar.c',
+       OCSRM_SRC + 'base64.c',
+       OCSRM_SRC + 'directpairing.c'
+       ]
+
 if env.get('SECURED') == '1':
-       libocsrm_src = [
-               OCSRM_SRC + 'secureresourcemanager.c',
-               OCSRM_SRC + 'resourcemanager.c',
-               OCSRM_SRC + 'aclresource.c',
-               OCSRM_SRC + 'amaclresource.c',
-               OCSRM_SRC + 'amsmgr.c',
-               OCSRM_SRC + 'pstatresource.c',
-               OCSRM_SRC + 'doxmresource.c',
-               OCSRM_SRC + 'credresource.c',
-               OCSRM_SRC + 'svcresource.c',
-               OCSRM_SRC + 'pconfresource.c',
-               OCSRM_SRC + 'dpairingresource.c',
-               OCSRM_SRC + 'verresource.c',
-               OCSRM_SRC + 'policyengine.c',
-               OCSRM_SRC + 'psinterface.c',
-               OCSRM_SRC + 'srmresourcestrings.c',
-               OCSRM_SRC + 'srmutility.c',
-               OCSRM_SRC + 'iotvticalendar.c',
-               OCSRM_SRC + 'oxmpincommon.c',
-               OCSRM_SRC + 'base64.c',
-               #pbkdf2.c is required to PIN based OxM only.
-               #But we did not use a separate build options to prevent the build command becomes complicated.
-               OCSRM_SRC + 'pbkdf2.c',
-               OCSRM_SRC + 'directpairing.c'
-               ]
-else:
-       libocsrm_src = [
-               OCSRM_SRC + 'secureresourcemanager.c',
-               OCSRM_SRC + 'resourcemanager.c',
-               OCSRM_SRC + 'aclresource.c',
-               OCSRM_SRC + 'amaclresource.c',
-               OCSRM_SRC + 'amsmgr.c',
-               OCSRM_SRC + 'pstatresource.c',
-               OCSRM_SRC + 'doxmresource.c',
-               OCSRM_SRC + 'credresource.c',
-               OCSRM_SRC + 'svcresource.c',
-               OCSRM_SRC + 'pconfresource.c',
-               OCSRM_SRC + 'dpairingresource.c',
-               OCSRM_SRC + 'policyengine.c',
-               OCSRM_SRC + 'verresource.c',
-               OCSRM_SRC + 'psinterface.c',
-               OCSRM_SRC + 'srmresourcestrings.c',
-               OCSRM_SRC + 'srmutility.c',
-               OCSRM_SRC + 'iotvticalendar.c',
-               OCSRM_SRC + 'base64.c',
-               OCSRM_SRC + 'directpairing.c'
-               ]
+       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' and env.get('SECURED') == '1':
        crl_src = [OCSRM_SRC + 'crlresource.c']
        libocsrm_src  = libocsrm_src + crl_src
 
+libocsrm_conf = Configure(libocsrm_env)
+if libocsrm_conf.CheckFunc('strptime'):
+       libocsrm_conf.env.AppendUnique(CPPDEFINES = ['HAVE_STRPTIME'])
+libocsrm_env = libocsrm_conf.Finish()
 
-libocsrm = libocsrm_env.StaticLibrary('libocsrm', libocsrm_src)
+libocsrm = libocsrm_env.StaticLibrary('ocsrm', libocsrm_src)
 
-libocsrm_env.InstallTarget(libocsrm, 'libocsrm')
+libocsrm_env.InstallTarget(libocsrm, 'ocsrm')
 
-if target_os in ['linux', 'android', 'tizen'] and env.get('SECURED') == '1':
+if target_os in ['linux', 'android', 'tizen', 'msys_nt', 'windows'] and env.get('SECURED') == '1':
        SConscript('provisioning/SConscript')
 
 if target_os in ['linux'] and env.get('SECURED') == '1':
index 5f1ac9d..2b83f81 100644 (file)
@@ -47,9 +47,9 @@ OCStackResult DeInitACLResource();
  *
  * @note On the first call to @ref GetACLResourceData, savePtr should point to NULL.
  *
- * @return reference to @ref OicSecAcl_t if ACL is found, else NULL.
+ * @return reference to @ref OicSecAce_t if ACE is found, else NULL.
  */
-const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **savePtr);
+const OicSecAce_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAce_t **savePtr);
 
 /**
  * This function converts ACL data into CBOR format.
@@ -70,6 +70,14 @@ OCStackResult AclToCBORPayload(const OicSecAcl_t * acl, uint8_t **outPayload, si
 void DeleteACLList(OicSecAcl_t* acl);
 
 /**
+ * Internal function to duplicate the ACE instance.
+ *
+ * @param ace instance of @ref OicSecAce_t structure to be duplicated.
+ * @return reference to @ref OicSecAce_t if ACE was successfully duplicated.
+ */
+OicSecAce_t* DuplicateACE(const OicSecAce_t* ace);
+
+/**
  * This function installs a new ACL.
  *
  * @param payload cbor value representing a new ACL.
@@ -80,12 +88,12 @@ void DeleteACLList(OicSecAcl_t* acl);
 OCStackResult InstallNewACL(const uint8_t* payload, const size_t size);
 
 /**
- * This function updates default ACL which is required for ownership transfer.
+ * 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.
  *
  * @retval OC_STACK_OK for Success, otherwise some error value
  */
-OCStackResult UpdateDefaultSecProvACL();
+OCStackResult UpdateDefaultSecProvACE();
 
 /**
  * Internal function to update resource owner
index 7e12912..a8d3e9f 100644 (file)
@@ -63,11 +63,12 @@ const OicSecCred_t* GetCredResourceData(const OicUuid_t* subjectId);
  * @param cred is the pointer to instance of OicSecCred_t structure.
  * @param cborPayload is the CBOR converted value.
  * @param cborSize is the size of the CBOR.
+ * @param secureFlag shows fill or not private key.
  *
  * @return ::OC_STACK_OK if conversion is successful, else ::OC_STACK_ERROR if unsuccessful.
  */
 OCStackResult CredToCBORPayload(const OicSecCred_t* cred, uint8_t **cborPayload,
-                                size_t *cborSize);
+                                size_t *cborSize, int secureFlag);
 
 /**
  * This function generates the bin credential data.
index 454bec7..3e98f8c 100644 (file)
@@ -51,7 +51,7 @@ uint8_t* GetCrl();
  *
  * @return encoded CRL with DER format. array len is 0 if error occured (e.g. CRL did not set).
  */
-void  GetDerCrl(ByteArray crlArray);
+void  GetDerCrl(ByteArray* crlArray);
 
 /**
  * This function converts CRL to CBOR
@@ -90,8 +90,10 @@ OCStackResult InitCRLResource();
 
 /**
  * Perform cleanup for CRL resources.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
-void DeInitCRLResource();
+OCStackResult DeInitCRLResource();
 
 /**
  * Get an instance of CRL resource.
index e884c9a..328523d 100644 (file)
@@ -43,6 +43,7 @@ OCStackResult DPDeviceDiscovery(unsigned short waittime);
 /**\r
  * Start direct-pairing processes.\r
  *\r
+ * @param[in] ctx  user context passed back with resultCallback.\r
  * @param[in] peer  target device to establish direct-pairing.\r
  * @param[in] pmSel  selected pairing method.\r
  * @param[in] pinNumber  secret value for dtls connection.\r
@@ -50,8 +51,8 @@ OCStackResult DPDeviceDiscovery(unsigned short waittime);
  *\r
  * @return OC_STACK_OK on success otherwise error.\r
  */\r
-OCStackResult DPDirectPairing(OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, char *pinNumber,\r
-                                                     OCDirectPairingResultCB resultCallback);\r
+OCStackResult DPDirectPairing(void *ctx, OCDirectPairingDev_t* peer, OicSecPrm_t pmSel,\r
+                                char *pinNumber, OCDirectPairingResultCB resultCallback);\r
 \r
 /**\r
  * This function returns discovered devices list in direct-pairing discovery\r
index c1900ac..7e84a76 100644 (file)
 
 #include "securevirtualresourcetypes.h"
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 extern const char * SVR_DB_FILE_NAME;
 extern const char * SVR_DB_DAT_FILE_NAME;
-extern const char * OIC_MI_DEF;
 
 //AMACL
 extern const char * OIC_RSRC_TYPE_SEC_AMACL;
@@ -110,6 +113,7 @@ extern const char * OIC_JSON_PUBDATA_NAME;
 extern const char * OIC_JSON_PRIVDATA_NAME;
 extern const char * OIC_JSON_OPTDATA_NAME;
 extern const char * OIC_JSON_CRMS_NAME;
+extern const char * OIC_JSON_VALIDITY_NAME;
 extern const char * OIC_JSON_PERIOD_NAME;
 extern const char * OIC_JSON_PERIODS_NAME;
 extern const char * OIC_JSON_RECURRENCES_NAME;
@@ -166,5 +170,9 @@ extern char OIC_SEC_REST_QUERY_DELIMETER;
 //Security Version
 extern const char * DEFAULT_SEC_VERSION;
 
+#ifdef __cplusplus
+}
+#endif
+
 #endif //IOTVT_SRM_RSRC_STRINGS_H
 
index 786658e..5cefddd 100644 (file)
@@ -47,6 +47,8 @@
 #include "byte_array.h"
 #endif /* __WITH_X509__ */
 
+#include "platform_features.h"
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -139,7 +141,7 @@ typedef enum
 /**
  * Extract Reason Code from Access Response.
  */
-static inline SRMAccessResponseReasonCode_t GetReasonCode(
+INLINE_API SRMAccessResponseReasonCode_t GetReasonCode(
     SRMAccessResponse_t response)
 {
     SRMAccessResponseReasonCode_t reason =
@@ -150,7 +152,7 @@ static inline SRMAccessResponseReasonCode_t GetReasonCode(
 /**
  * Returns 'true' iff request should be passed on to RI layer.
  */
-static inline bool IsAccessGranted(SRMAccessResponse_t response)
+INLINE_API bool IsAccessGranted(SRMAccessResponse_t response)
 {
     if(ACCESS_GRANTED == (response & ACCESS_GRANTED))
     {
@@ -162,6 +164,12 @@ static inline bool IsAccessGranted(SRMAccessResponse_t response)
     }
 }
 
+typedef struct OicSecRsrc OicSecRsrc_t;
+
+typedef struct OicSecValidity OicSecValidity_t;
+
+typedef struct OicSecAce OicSecAce_t;
+
 typedef struct OicSecAcl OicSecAcl_t;
 
 typedef struct OicSecAmacl OicSecAmacl_t;
@@ -261,6 +269,13 @@ typedef enum
     OIC_OXM_COUNT
 }OicSecOxm_t;
 
+typedef enum
+{
+    OIC_ENCODING_UNKNOW = 0,
+    OIC_ENCODING_RAW = 1,
+    OIC_ENCODING_BASE64 = 2
+}OicEncodingType_t;
+
 typedef struct OicSecKey OicSecKey_t;
 
 typedef struct OicSecPstat OicSecPstat_t;
@@ -308,6 +323,39 @@ struct OicSecKey
 {
     uint8_t                *data;
     size_t                  len;
+
+    // TODO: This field added as workaround. Will be replaced soon.
+    OicEncodingType_t encoding;
+
+};
+
+struct OicSecRsrc
+{
+    char *href; // 0:R:S:Y:String
+    char *rel; // 1:R:S:N:String
+    char** types; // 2:R:S:N:String Array
+    size_t typeLen; // the number of elts in types
+    char** interfaces; // 3:R:S:N:String Array
+    size_t interfaceLen; // the number of elts in interfaces
+    OicSecRsrc_t *next;
+};
+
+struct OicSecValidity
+{
+    char* period; // 0:R:S:Y:String
+    char** recurrences; // 1:R:M:Y:Array of String
+    size_t recurrenceLen; // the number of elts in recurrence
+    OicSecValidity_t *next;
+};
+
+struct OicSecAce
+{
+    // <Attribute ID>:<Read/Write>:<Multiple/Single>:<Mandatory?>:<Type>
+    OicUuid_t subjectuuid; // 0:R:S:Y:uuid
+    OicSecRsrc_t *resources; // 1:R:M:Y:Resource
+    uint16_t permission; // 2:R:S:Y:UINT16
+    OicSecValidity_t *validities; // 3:R:M:N:Time-interval
+    OicSecAce_t *next;
 };
 
 /**
@@ -317,17 +365,8 @@ struct OicSecKey
 struct OicSecAcl
 {
     // <Attribute ID>:<Read/Write>:<Multiple/Single>:<Mandatory?>:<Type>
-    OicUuid_t           subject;        // 0:R:S:Y:uuid TODO: this deviates
-                                        // from spec and needs to be updated
-                                        // in spec (where it's a String).
-    size_t              resourcesLen;   // the number of elts in Resources
-    char                **resources;    // 1:R:M:Y:String
-    uint16_t            permission;     // 2:R:S:Y:UINT16
-    size_t              prdRecrLen;     // the number of elts in Periods
-    char                **periods;       // 3:R:M*:N:String (<--M*; see Spec)
-    char                **recurrences;   // 5:R:M:N:String
-    OicUuid_t           rownerID;        // 8:R:S:Y:oic.uuid
-    OicSecAcl_t         *next;
+    OicUuid_t           rownerID;        // 0:R:S:Y:oic.uuid
+    OicSecAce_t         *aces; // 1:R:M:N:ACE
 };
 
 /**
@@ -428,6 +467,9 @@ struct OicSecSacl
 {
     // <Attribute ID>:<Read/Write>:<Multiple/Single>:<Mandatory?>:<Type>
     //TODO fill in from OIC Security Spec
+#if defined(_MSC_VER)
+    uint8_t unused; // VS doesn't like empty structs
+#endif
 };
 
 /**
index 329aaca..2fea369 100644 (file)
@@ -33,13 +33,13 @@ provisioning_env.AppendUnique(CPPPATH = [
                '../../../c_common/ocrandom/include',
                '../../logger/include',
                '../../../oc_logger/include',
-               '../../ocmalloc/include',
+               '../../../c_common/oic_malloc/include',
                'include',
                'include/internal',
                'include/oxm',
                '../../resource/csdk/security/include',
                '../../../../extlibs/cjson/',
-               '../../../../../extlibs/tinydtls/',
+               '../../../../extlibs/tinydtls/',
                '../../connectivity/inc',
                '../../connectivity/external/inc',
                '../../connectivity/common/inc',
@@ -57,17 +57,17 @@ target_os = env.get('TARGET_OS')
 if target_os != 'tizen':
        provisioning_env.AppendUnique(CPPPATH = ['../../../../extlibs/sqlite3'])
 
-provisioning_env.AppendUnique(CFLAGS = ['-D__WITH_DTLS__'])
-provisioning_env.AppendUnique(CFLAGS = ['-std=c99'])
-if target_os not in ['windows', 'winrt']:
-       provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread', '-D__WITH_DTLS__'])
+provisioning_env.AppendUnique(CPPDEFINES= ['__WITH_DTLS__'])
+if target_os not in ['windows']:
+       provisioning_env.AppendUnique(CFLAGS = ['-std=c99'])
+if target_os not in ['windows', 'msys_nt']:
+       provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
 
        # Note: 'pthread' is in libc for android. On other platform, if use
        # new gcc(>4.9?) it isn't required, otherwise, it's required
        if target_os != 'android':
                provisioning_env.AppendUnique(LIBS = ['-lpthread', '-ldl'])
 
-
 provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 provisioning_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap'])
 
@@ -76,9 +76,12 @@ provisioning_env.AppendUnique(LIBS = ['tinydtls'])
 if env.get('DTLS_WITH_X509') == '1':
        provisioning_env.AppendUnique(LIBS = ['CKManager', 'asn1'])
 
-if target_os != 'android':
+if target_os not in ['msys_nt', 'windows', 'android']:
        provisioning_env.ParseConfig('pkg-config --libs glib-2.0')
 
+if target_os in ['windows', 'msys_nt']:
+       provisioning_env.AppendUnique(LIBS = ['ws2_32', 'advapi32', 'iphlpapi', 'timer'])
+
 if target_os == 'tizen':
        provisioning_env.ParseConfig('pkg-config --cflags --libs sqlite3')
 
@@ -108,14 +111,18 @@ provisioning_src = [
 if target_os != 'tizen':
        provisioning_src = provisioning_src + [root_dir+'/extlibs/sqlite3/sqlite3.c' ]
 
-provisioningserver = provisioning_env.SharedLibrary('ocpmapi', provisioning_src)
+if target_os == 'windows':
+       # TODO: Add OC_EXPORT annotations and enable generation of Windows DLL
+       provisioningserver = provisioning_env.StaticLibrary('ocpmapi', provisioning_src)
+else:
+       provisioningserver = provisioning_env.SharedLibrary('ocpmapi', provisioning_src)
 
-provisioning_env.InstallTarget(provisioningserver, 'libocpmapi')
-provisioning_env.UserInstallTargetLib(provisioningserver, 'libocpmapi')
+provisioning_env.InstallTarget(provisioningserver, 'ocpmapi')
+provisioning_env.UserInstallTargetLib(provisioningserver, 'ocpmapi')
 
 if env.get('DTLS_WITH_X509') == '1':
        SConscript('ck_manager/SConscript')
 
-if target_os in ['linux']:
+if target_os in ['linux', 'msys_nt', 'windows']:
        SConscript('sample/SConscript')
 
old mode 100755 (executable)
new mode 100644 (file)
index bf440f2..75ef688
Binary files a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat and b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat differ
old mode 100755 (executable)
new mode 100644 (file)
index 20062b4..ac98158
@@ -8,38 +8,18 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
+                        },{\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
+                        },{\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/presence",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
-                            "href": "/oic/sec/crl",\r
+                            "href": "/oic/sec/cred",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.cred"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
-                            "href": "/oic/sec/cred",\r
+                            "href": "/oic/sec/crl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.crl"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 6\r
         "owned": false,\r
         "deviceuuid": "646F6F72-4465-7669-6365-555549443030",\r
         "rowneruuid": "646F6F72-4465-7669-6365-555549443030",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     }\r
 }
old mode 100755 (executable)
new mode 100644 (file)
index 59f65e5..f5c6a1a
Binary files a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat and b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat differ
old mode 100755 (executable)
new mode 100644 (file)
index a7598d4..8843b87
@@ -8,38 +8,18 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
+                        },{\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
+                        },{\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/presence",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
-                            "href": "/oic/sec/crl",\r
+                            "href": "/oic/sec/cred",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.cred"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
-                            "href": "/oic/sec/cred",\r
+                            "href": "/oic/sec/crl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.crl"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 6\r
         "owned": false,\r
         "deviceuuid": "6C696768-7444-6576-6963-655555494430",\r
         "rowneruuid": "6C696768-7444-6576-6963-655555494430",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     }\r
 }
old mode 100755 (executable)
new mode 100644 (file)
index 6143d32..9571397
Binary files a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat and b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat differ
old mode 100755 (executable)
new mode 100644 (file)
index 2e33796..90c4e3a
@@ -8,32 +8,18 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
+                        },{\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
+                        },{\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/ad",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        } ,\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
@@ -77,6 +63,6 @@
         "deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
         "devowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
         "rowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     }\r
 }
\ No newline at end of file
index 91a7619..dc7485d 100644 (file)
@@ -37,6 +37,7 @@
 
 #define MAX_URI_LENGTH (64)
 #define MAX_PERMISSION_LENGTH (5)
+#define MAX_ACL_LENGTH 100
 #define CREATE (1)
 #define READ (2)
 #define UPDATE (4)
@@ -71,7 +72,7 @@ typedef enum
  */
 static void deleteACL(OicSecAcl_t *acl)
 {
-    if (acl)
+    if (acl && MAX_ACL_LENGTH > acl->resourcesLen)
     {
         /* Clean Resources */
         for (size_t i = 0; i < (acl)->resourcesLen; i++)
@@ -214,7 +215,7 @@ static int InputACL(OicSecAcl_t *acl)
     //Set Resource.
     printf("Num. of Resource : \n");
     ret = scanf("%zu", &acl->resourcesLen);
-    if(-1 == ret)
+    if(-1 == ret || MAX_ACL_LENGTH < acl->resourcesLen)
     {
         printf("Error while input\n");
         return -1;
index 6218806..7a6f072 100644 (file)
@@ -68,14 +68,19 @@ if not env.get('RELEASE'):
 ######################################################################
 # Source files and Targets
 ######################################################################
-unittest = pki_test_env.Program('unittest', ['pki_test.cpp'])
+unittest = pki_test_env.Program('unittest', ['pki_test.cpp',
+                                            'ckm_info_test.cpp',
+                                            'crl_generator_test.cpp',
+                                            'csr_generator_test.cpp'])
 
 Alias("test", [unittest])
 
 
 
 unittest_src_dir = src_dir + '/resource/csdk/security/provisioning/ck_manager/unittest/test_data/'
-unittest_build_dir = env.get('BUILD_DIR') +'/resource/csdk/security/provisioning/ck_manager/unittest'
+unittest_build_dir = env.get('BUILD_DIR') +'resource/csdk/security/provisioning/ck_manager/unittest'
+
+pki_test_env.AppendUnique(CPPDEFINES = ['SECURITY_BUILD_UNITTEST_DIR='+unittest_build_dir])
 
 pki_test_env.Alias("install",env.Install( unittest_build_dir, [ unittest_src_dir + '01.der',
                                                                unittest_src_dir + 'cacert.der',
@@ -95,6 +100,6 @@ if env.get('TEST') == '1':
                pki_test_env.AppendENVPath('GTEST_OUTPUT', ['xml:'+ result_dir])
                pki_test_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir])
                pki_test_env.AppendENVPath('LD_LIBRARY_PATH', [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs'])
-               ut = pki_test_env.Command ('ut', None, out_dir + '/resource/csdk/security/unittest/unittest')
+               ut = pki_test_env.Command ('ut', None, out_dir + '/resource/csdk/security/provisioning/ck_manager/unittest/unittest')
 AlwaysBuild ('ut')
 
diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/ckm_info_test.cpp b/resource/csdk/security/provisioning/ck_manager/unittest/ckm_info_test.cpp
new file mode 100644 (file)
index 0000000..66d6cb1
--- /dev/null
@@ -0,0 +1,272 @@
+/******************************************************************
+ *
+ * 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
+ *
+ *      LICENSE-2.0" target="_blank">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 <gtest/gtest.h>
+#include "ckm_info.h"
+
+#define ISSUER_NAME_SIZE (16)
+#define CERT_LEN 469
+
+class CKMInfoTest : public ::testing::Test
+{
+public:
+    static void SetUpTestCase()
+    {
+    }
+
+    static void TearDownTestCase()
+    {
+    }
+
+    static const ByteArray publicKey;
+    static const ByteArray privateKey;
+    static const ByteArray derCode ;
+    static const long nextSN;
+    static const long crlSerialNum;
+    static const ByteArray caName;
+};
+
+const ByteArray CKMInfoTest::publicKey = {(uint8_t[])
+{
+    0x8c, 0xc8, 0x92, 0x1d, 0xaa, 0x7f, 0xf0, 0xe4, 0xb2, 0x75, 0xd6, 0x4a, 0xf1, 0xd5, 0x14, 0x3f,
+    0x1a, 0x09, 0xc5, 0x3e, 0x52, 0xd6, 0xda, 0xa0, 0xbf, 0x90, 0x43, 0xd1, 0x6b, 0xfe, 0xd1, 0xb3,
+    0x75, 0x5c, 0xdd, 0x69, 0xac, 0x42, 0xa1, 0xcb, 0x03, 0x16, 0xee, 0xa4, 0x30, 0xa5, 0x8d, 0x36,
+    0x8f, 0xc5, 0x7b, 0xb4, 0xb5, 0x6a, 0x7d, 0x9b, 0x16, 0x04, 0x46, 0xab, 0xae, 0xbb, 0x56, 0xa1
+}, PUBLIC_KEY_SIZE };
+
+const ByteArray CKMInfoTest::privateKey = {(uint8_t[])
+{
+    0xd6, 0xc8, 0x92, 0x16, 0x36, 0x7f, 0xf0, 0xe4, 0xb2, 0x75, 0xd6, 0x4a, 0xf1, 0x3f, 0x14, 0x30,
+    0x1a, 0x69, 0xc5, 0x3e, 0x52, 0xd6, 0xda, 0xa0, 0xbf, 0xae, 0x43, 0xd1, 0x6b, 0xfe, 0xd1, 0x36
+}, PRIVATE_KEY_SIZE };
+
+const ByteArray CKMInfoTest::derCode = {(uint8_t[])
+    {
+        0x30, 0x82, 0x01, 0xd1, 0x30, 0x82, 0x01, 0x77, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x09, 0x00,
+        0xd7, 0x56, 0x8c, 0xfc, 0x53, 0x18, 0xb0, 0xab, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce,
+        0x3d, 0x04, 0x03, 0x02, 0x30, 0x45, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
+        0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f,
+        0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04,
+        0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67,
+        0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 0x30, 0x1e, 0x17, 0x0d, 0x31,
+        0x35, 0x30, 0x33, 0x31, 0x32, 0x31, 0x32, 0x32, 0x35, 0x31, 0x31, 0x5a, 0x17, 0x0d, 0x31, 0x37,
+        0x30, 0x33, 0x31, 0x31, 0x31, 0x32, 0x32, 0x35, 0x31, 0x31, 0x5a, 0x30, 0x45, 0x31, 0x0b, 0x30,
+        0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03,
+        0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31,
+        0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e,
+        0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c,
+        0x74, 0x64, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06,
+        0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x8c, 0xc8, 0x92,
+        0x1d, 0xaa, 0x7f, 0xf0, 0xe4, 0xb2, 0x75, 0xd6, 0x4a, 0xf1, 0xd5, 0x14, 0x3f, 0x1a, 0x09, 0xc5,
+        0x3e, 0x52, 0xd6, 0xda, 0xa0, 0xbf, 0x90, 0x43, 0xd1, 0x6b, 0xfe, 0xd1, 0xb3, 0x75, 0x5c, 0xdd,
+        0x69, 0xac, 0x42, 0xa1, 0xcb, 0x03, 0x16, 0xee, 0xa4, 0x30, 0xa5, 0x8d, 0x36, 0x8f, 0xc5, 0x7b,
+        0xb4, 0xb5, 0x6a, 0x7d, 0x9b, 0x16, 0x04, 0x46, 0xab, 0xae, 0xbb, 0x56, 0xa1, 0xa3, 0x50, 0x30,
+        0x4e, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x5c, 0x0e, 0x30, 0xa8,
+        0x8e, 0x7f, 0xc9, 0x02, 0xcd, 0xa8, 0xed, 0x0d, 0x1a, 0x1b, 0xd9, 0x7d, 0xe6, 0xce, 0x2a, 0x59,
+        0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x5c, 0x0e, 0x30,
+        0xa8, 0x8e, 0x7f, 0xc9, 0x02, 0xcd, 0xa8, 0xed, 0x0d, 0x1a, 0x1b, 0xd9, 0x7d, 0xe6, 0xce, 0x2a,
+        0x59, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30,
+        0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45,
+        0x02, 0x21, 0x00, 0xf6, 0x79, 0xed, 0x69, 0xd5, 0xe5, 0xba, 0x42, 0x14, 0xfc, 0xce, 0x47, 0xf1,
+        0x61, 0x1c, 0x51, 0x11, 0x2b, 0xba, 0x04, 0x70, 0x56, 0x78, 0xaf, 0xa9, 0xa6, 0x98, 0x8f, 0x4b,
+        0xa8, 0x11, 0x67, 0x02, 0x20, 0x3a, 0xdf, 0xf1, 0x74, 0xc9, 0x2f, 0xfb, 0x84, 0x46, 0xde, 0xbc,
+        0x2d, 0xda, 0xe3, 0x05, 0xb4, 0x81, 0x31, 0x45, 0xf7, 0x3d, 0x71, 0x46, 0x07, 0xa7, 0xd8, 0xcb,
+        0xae, 0x1e, 0x1b, 0x1c, 0x5a
+    }, CERT_LEN };
+
+const long CKMInfoTest::nextSN = 0x111111;
+
+const long CKMInfoTest::crlSerialNum = 0x22222;
+
+const ByteArray CKMInfoTest::caName = {(uint8_t[])
+{
+    0x1a, 0x1a, 0x1a, 0x1d, 0xaa, 0x7f, 0xf0, 0xe4, 0xb2, 0x75, 0xd6, 0x4a, 0xf1, 0xd5, 0x14, 0x3f
+}, ISSUER_NAME_SIZE };
+
+//InitCRT test
+TEST(CKMInfoTest, InitCRT)
+{
+    ASSERT_EQ(PKI_SUCCESS, InitCRT());
+}
+
+//SaveCRT test
+TEST(CKMInfoTest, SaveCRT)
+{
+    ASSERT_EQ(PKI_SUCCESS, SaveCRT());
+}
+
+//InitCRL test
+TEST(CKMInfoTest, InitCRL)
+{
+    ASSERT_EQ(PKI_SUCCESS, InitCRL());
+}
+
+//SaveCRL test
+TEST(CKMInfoTest, SaveCRL)
+{
+    ASSERT_EQ(PKI_SUCCESS, SaveCRL());
+}
+
+//InitCKMInfo test
+TEST(CKMInfoTest, InitCKMInfo)
+{
+    ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
+}
+
+//SaveCKMInfo test
+TEST(CKMInfoTest, SaveCKMInfo)
+{
+    ASSERT_EQ(PKI_SUCCESS, SaveCKMInfo());
+}
+
+//SetGetNextSerialNumber test
+TEST(CKMInfoTest, SetGetNextSerialNumber)
+{
+    ASSERT_EQ(PKI_SUCCESS, SetNextSerialNumber(CKMInfoTest::nextSN));
+    long nSn = 0;
+    ASSERT_EQ(PKI_SUCCESS, GetNextSerialNumber(&nSn));
+    EXPECT_TRUE(nSn == CKMInfoTest::nextSN);
+}
+
+//SetGetCAPrivateKey test
+TEST(CKMInfoTest, SetGetCAPrivateKey)
+{
+    ASSERT_EQ(PKI_SUCCESS, SetCAPrivateKey(&CKMInfoTest::privateKey));
+
+    ByteArray privateKey = {0,0};
+    uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0};
+
+    privateKey.data = caPrivKey;
+    privateKey.len = PRIVATE_KEY_SIZE;
+
+    EXPECT_EQ(PKI_SUCCESS, GetCAPrivateKey(&privateKey));
+    EXPECT_TRUE(0 == memcmp(CKMInfoTest::privateKey.data, privateKey.data, PRIVATE_KEY_SIZE));
+}
+
+//SetGetCAPublicKey test
+TEST(CKMInfoTest, SetGetCAPublicKey)
+{
+    ASSERT_EQ(PKI_SUCCESS, SetCAPublicKey(&CKMInfoTest::publicKey));
+
+    ByteArray publicKey = {0,0};
+    uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
+
+    publicKey.data = caPubKey;
+    publicKey.len = PUBLIC_KEY_SIZE;
+
+    EXPECT_EQ(PKI_SUCCESS, GetCAPublicKey(&publicKey));
+    EXPECT_TRUE(0 == memcmp(CKMInfoTest::publicKey.data, publicKey.data, PUBLIC_KEY_SIZE));
+}
+
+//SetGetCAName test
+TEST(CKMInfoTest, SetGetCAName)
+{
+    ASSERT_EQ(PKI_SUCCESS, SetCAName(&CKMInfoTest::caName));
+
+    ByteArray caName = {0,0};
+    uint8_t caIssName[PUBLIC_KEY_SIZE] = {0};
+
+    caName.data = caIssName;
+    caName.len = ISSUER_NAME_SIZE;
+
+    EXPECT_EQ(PKI_SUCCESS, GetCAName(&caName));
+    EXPECT_TRUE(0 == memcmp(CKMInfoTest::caName.data, caName.data, ISSUER_NAME_SIZE));
+}
+
+//SetGetCKMInfo test
+TEST(CKMInfoTest, SetGetCKMInfo)
+{
+    ASSERT_EQ(PKI_SUCCESS, SetCKMInfo(CKMInfoTest::nextSN, CKMInfoTest::crlSerialNum,
+            &CKMInfoTest::privateKey, &CKMInfoTest::publicKey, &CKMInfoTest::caName));
+
+    long nSn = 0;
+    long serialNum = 0;
+
+    ByteArray publicKey = {0,0};
+    uint8_t caIssName[ISSUER_MAX_CERT_SIZE] = {0};
+    uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
+    uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0};
+
+    publicKey.data = caPubKey;
+    publicKey.len = PUBLIC_KEY_SIZE;
+
+    ByteArray privateKey = {0,0};
+    privateKey.data = caPrivKey;
+    privateKey.len = PRIVATE_KEY_SIZE;
+
+    ByteArray caName = {0,0};
+    caName.data = caIssName;
+    caName.len = ISSUER_NAME_SIZE;
+
+    EXPECT_EQ(PKI_SUCCESS, GetCKMInfo(&nSn, &serialNum,
+            &privateKey, &publicKey, &caName));
+
+    EXPECT_TRUE(nSn == CKMInfoTest::nextSN);
+    EXPECT_TRUE(serialNum == CKMInfoTest::crlSerialNum);
+    EXPECT_TRUE(0 == memcmp(CKMInfoTest::privateKey.data, privateKey.data, PRIVATE_KEY_SIZE));
+    EXPECT_TRUE(0 == memcmp(CKMInfoTest::publicKey.data, publicKey.data, PUBLIC_KEY_SIZE));
+    EXPECT_TRUE(0 == memcmp(CKMInfoTest::caName.data, caName.data, ISSUER_NAME_SIZE));
+}
+
+//SetGetCACertificate test
+TEST(CKMInfoTest, SetGetCACertificate)
+{
+    ASSERT_EQ(PKI_SUCCESS, SetCACertificate(&CKMInfoTest::derCode));
+
+    ByteArray der = {0,0};
+    uint8_t caCert[CERT_LEN] = {0};
+    der.data = caCert;
+    der.len = CERT_LEN;
+    EXPECT_TRUE(NULL != der.data);
+    EXPECT_EQ(PKI_SUCCESS, GetCACertificate(&der));
+    EXPECT_TRUE(0 == memcmp(CKMInfoTest::derCode.data, der.data, CERT_LEN));
+}
+
+//SetGetCRLSerialNumber test
+TEST(CKMInfoTest, SetGetCRLSerialNumber)
+{
+    ASSERT_EQ(PKI_SUCCESS, SetCRLSerialNumber(CKMInfoTest::crlSerialNum));
+    long serialNum = 0;
+    ASSERT_EQ(PKI_SUCCESS, GetCRLSerialNumber(&serialNum));
+    EXPECT_TRUE(serialNum == CKMInfoTest::crlSerialNum);
+}
+
+//SetGetNumberOfRevoked test
+TEST(CKMInfoTest, SetGetNumberOfRevoked)
+{
+    const long NUM_OF_REVOKED = 5;
+    ASSERT_EQ(PKI_SUCCESS, SetNumberOfRevoked(NUM_OF_REVOKED));
+    long numRev = 0;
+    ASSERT_EQ(PKI_SUCCESS, GetNumberOfRevoked(&numRev));
+    EXPECT_TRUE(numRev == NUM_OF_REVOKED);
+}
+
+//SetCertificateRevocationList test
+TEST(CKMInfoTest, SetCertificateRevocationList)
+{
+    ASSERT_EQ(PKI_SUCCESS, SetCertificateRevocationList(&CKMInfoTest::derCode));
+}
+
+//CloseCKMInfo test
+TEST(CKMInfoTest, CloseCKMInfo)
+{
+    ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo());
+}
diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/crl_generator_test.cpp b/resource/csdk/security/provisioning/ck_manager/unittest/crl_generator_test.cpp
new file mode 100644 (file)
index 0000000..93d0343
--- /dev/null
@@ -0,0 +1,98 @@
+/******************************************************************
+ *
+ * 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
+ *
+ *      LICENSE-2.0" target="_blank">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 <oic_malloc.h>
+#include <gtest/gtest.h>
+#include "crl_generator.h"
+
+static const ByteArray privateKey = {(uint8_t[])
+{
+       0xd6, 0xc8, 0x92, 0x16, 0x36, 0x7f, 0xf0, 0xe4, 0xb2, 0x75, 0xd6, 0x4a, 0xf1, 0x3f, 0x14, 0x30,
+    0x1a, 0x69, 0xc5, 0x3e, 0x52, 0xd6, 0xda, 0xa0, 0xbf, 0xae, 0x43, 0xd1, 0x6b, 0xfe, 0xd1, 0x36
+}, PRIVATE_KEY_SIZE };
+
+//GenerateCRL test
+TEST(CRLGeneratorTest, GenerateCRL)
+{
+    uint8_t *uint8ThisUpdateTime = (uint8_t *)"130101000000Z";
+    uint32_t numberOfRevoked = 2;
+    uint32_t revokedNumbers[2];
+    const uint8_t *revocationDates[2];
+    CertificateRevocationInfo_t *certificateRevocationInfo = NULL;
+    UTF8String_t *issuerName = NULL;
+    UTCTime_t *thisUpdateTime = NULL;
+    ByteArray encodedCRL = BYTE_ARRAY_INITIALIZER;
+    BIT_STRING_t issuerPrivateKey;
+
+    revokedNumbers[0] = 100; // serial number of first revoked certificate
+    revokedNumbers[1] = 200; // serial number of second revoked certificate
+
+    revocationDates[0] = (const uint8_t *)"130101000001Z";
+    revocationDates[1] = (const uint8_t *)"130101000002Z";
+
+    certificateRevocationInfo = (CertificateRevocationInfo_t *)OICCalloc(numberOfRevoked,
+            sizeof(CertificateRevocationInfo_t));
+    EXPECT_TRUE(NULL != certificateRevocationInfo);
+
+    issuerName = (UTF8String_t *)OICCalloc(1, sizeof(UTF8String_t));
+    EXPECT_TRUE(NULL != issuerName);
+
+    thisUpdateTime = (UTCTime_t *)OICCalloc(1, sizeof(UTCTime_t));
+    EXPECT_TRUE(NULL != thisUpdateTime);
+
+    encodedCRL.data = (uint8_t *)OICCalloc(1,
+                (CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4)));
+    EXPECT_TRUE(NULL != encodedCRL.data);
+    encodedCRL.len = (CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4));
+
+    issuerPrivateKey.size = PRIVATE_KEY_SIZE + 1;
+    issuerPrivateKey.buf = (uint8_t *)OICCalloc((issuerPrivateKey.size), sizeof(uint8_t));
+    EXPECT_TRUE(NULL != issuerPrivateKey.buf);
+
+    if(NULL != certificateRevocationInfo && NULL != issuerName &&
+            NULL != thisUpdateTime && NULL != encodedCRL.data && NULL != issuerPrivateKey.buf)
+    {
+        ByteArray issName = BYTE_ARRAY_INITIALIZER;
+        issName.data = (uint8_t *)"Issuer";
+        issName.len = strlen((char *)issName.data);
+
+        issuerName->buf  = issName.data;
+        issuerName->size = issName.len;
+
+        for (size_t i = 0; i < numberOfRevoked; i++ )
+        {
+            certificateRevocationInfo[i].userCertificate = revokedNumbers[i];
+            certificateRevocationInfo[i].revocationDate.buf = (uint8_t *)revocationDates[i];
+            certificateRevocationInfo[i].revocationDate.size =
+                     strlen((const char *)revocationDates[i]);
+        }
+
+        memcpy((issuerPrivateKey.buf) + 1, privateKey.data, PRIVATE_KEY_SIZE);
+
+        EXPECT_EQ(PKI_SUCCESS, GenerateCRL(issuerName, thisUpdateTime, numberOfRevoked,
+                certificateRevocationInfo, &issuerPrivateKey, &encodedCRL));
+    }
+
+    OICFree(certificateRevocationInfo);
+    OICFree(issuerName);
+    OICFree(thisUpdateTime);
+}
+
diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/csr_generator_test.cpp b/resource/csdk/security/provisioning/ck_manager/unittest/csr_generator_test.cpp
new file mode 100644 (file)
index 0000000..c94f3c5
--- /dev/null
@@ -0,0 +1,110 @@
+/******************************************************************
+ *
+ * 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
+ *
+ *      LICENSE-2.0" target="_blank">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 <gtest/gtest.h>
+#include "ck_manager.h"
+#include "crl_generator.h"
+#include "pki.h"
+#include "oic_malloc.h"
+#include "ckm_info.h"
+#define ASN1_UNCOMPRESSED_KEY_ID   (0x04)
+
+//EncodeDecodeCSR test
+TEST(CSRGeneratorTest, EncodeDecodeCSR)
+{
+    uint8_t csrData[CSR_MAX_SIZE] = {0};
+    uint8_t subjPubKey[PUBLIC_KEY_SIZE] = {0};
+    uint8_t subjPrivKey[PRIVATE_KEY_SIZE] = {0};
+    ByteArray pubKeySubj = BYTE_ARRAY_INITIALIZER;
+    ByteArray privKeySubj = BYTE_ARRAY_INITIALIZER;
+    uint8_t *subjName = (uint8_t *)"Subject05";
+    UTF8String_t* subjectName = NULL;
+    BIT_STRING_t* subjectPublicKey = NULL;
+    BIT_STRING_t* subjectPrivateKey = NULL;
+    ByteArray csrDer = BYTE_ARRAY_INITIALIZER;
+    BIT_STRING_t* subjectPublicKeyOut = NULL;
+    UTF8String_t* subjectNameOut = NULL;
+    uint8_t uint8SubjectName[ISSUER_MAX_NAME_SIZE];
+    uint8_t uint8SubjectPublicKey[PUBLIC_KEY_SIZE + 1];
+
+    csrDer.data = csrData;
+    csrDer.len = CSR_MAX_SIZE;
+
+    pubKeySubj.data = subjPubKey;
+    pubKeySubj.len = sizeof(subjPubKey);
+    privKeySubj.data = subjPrivKey;
+    privKeySubj.len = sizeof(subjPrivKey);
+
+    ASSERT_EQ(PKI_SUCCESS, GenerateKeyPair(&privKeySubj, &pubKeySubj));
+
+    subjectName = (UTF8String_t*)OICCalloc(1, sizeof(UTF8String_t));
+    EXPECT_TRUE(NULL != subjectName);
+
+    subjectPublicKey = (BIT_STRING_t*)OICCalloc(1, sizeof(BIT_STRING_t));
+    EXPECT_TRUE(NULL != subjectPublicKey);
+
+    subjectPrivateKey = (BIT_STRING_t*)OICCalloc(1, sizeof(BIT_STRING_t));
+    EXPECT_TRUE(NULL != subjectPrivateKey);
+
+    if(NULL != subjectName && NULL != subjectPublicKey && NULL != subjectPrivateKey)
+    {
+        subjectName->buf  = (uint8_t *)subjName;
+        subjectName->size = strlen((const char *)subjectName->buf);
+
+        subjectPrivateKey->size = PRIVATE_KEY_SIZE + 1;
+        subjectPrivateKey->buf = (uint8_t *)OICCalloc((subjectPrivateKey->size), sizeof(uint8_t));
+        EXPECT_TRUE(NULL != subjectPrivateKey->buf);
+
+        subjectPublicKey->size = PUBLIC_KEY_SIZE + 1;
+        subjectPublicKey->buf = (uint8_t *)OICCalloc(subjectPublicKey->size, sizeof(uint8_t));
+        EXPECT_TRUE(NULL != subjectPublicKey->buf);
+
+        if(NULL!= subjectPublicKey->buf && NULL != subjectPrivateKey->buf)
+        {
+            memcpy((subjectPrivateKey->buf) + 1, subjPrivKey, PRIVATE_KEY_SIZE);
+            memcpy((subjectPublicKey->buf) + 1, subjPubKey, PUBLIC_KEY_SIZE);
+
+            EXPECT_EQ(PKI_SUCCESS, EncodeCSR(subjectName, subjectPublicKey, subjectPrivateKey, &csrDer));
+        }
+    }
+
+    subjectPublicKeyOut = (BIT_STRING_t*)OICCalloc(1, sizeof(BIT_STRING_t));
+    EXPECT_TRUE(NULL != subjectPublicKey);
+
+    subjectNameOut = (UTF8String_t*)OICCalloc(1, sizeof(UTF8String_t));
+    EXPECT_TRUE(NULL != subjectNameOut);
+
+    if(NULL != subjectNameOut && NULL != subjectPublicKeyOut)
+    {
+        subjectNameOut->buf = uint8SubjectName;
+        subjectPublicKeyOut->buf = uint8SubjectPublicKey;
+        EXPECT_EQ(PKI_SUCCESS, DecodeCSR(&csrDer, subjectNameOut, subjectPublicKeyOut));
+    }
+
+    OICFree(subjectName);
+    OICFree(subjectPublicKey);
+    OICFree(subjectNameOut);
+    OICFree(subjectPublicKeyOut);
+    if (subjectPrivateKey)
+    {
+        OICFree(subjectPrivateKey->buf);
+        OICFree(subjectPrivateKey);
+    }
+}
index e224b42..649888a 100644 (file)
@@ -60,6 +60,23 @@ FILE* ckm_fopen(const char * /*path*/, const char *mode)
     return fopen(CKMI_PS_FILE_NAME, mode);
 }
 
+#define STRINGIZE2(x) #x
+#define STRINGIZE(x) STRINGIZE2(x)
+
+static char* resolve_file_path(const char* filename )
+{
+    int len = strlen(STRINGIZE(SECURITY_BUILD_UNITTEST_DIR)) + strlen(filename) + 1;
+    char *filepath = (char *)OICCalloc(1, len);
+
+    if (!filepath)
+    {
+        printf("filepath memory allocation failed. \n");
+        return NULL;
+    }
+    int ret = snprintf(filepath, len, "%s%s", STRINGIZE(SECURITY_BUILD_UNITTEST_DIR), filename);
+    return filepath;
+}
+
 void SetPersistentHandler(OCPersistentStorage *ps)
 {
     if(ps)
@@ -369,6 +386,7 @@ TEST(X509Certificate, testParsePublicKey)
 TEST(OpenSSLCompatibility, verifyOpenSslCertSign)
 {
     struct stat st;
+    char *fpath = NULL;
     uint8_t crtData[ISSUER_MAX_CERT_SIZE] = {0};
     uint8_t pubKeyData[PUBLIC_KEY_SIZE] = {0};
     ByteArray crtDer = BYTE_ARRAY_INITIALIZER;
@@ -381,7 +399,10 @@ TEST(OpenSSLCompatibility, verifyOpenSslCertSign)
     pubKey.len = sizeof(pubKeyData);
 
     //open file
-    int fileCert = open("01.der", O_RDONLY);
+    fpath = resolve_file_path("/01.der");
+    int fileCert = open(fpath, O_RDONLY);
+    OICFree(fpath);
+
     ASSERT_TRUE(fileCert != -1);
     //get status
     ASSERT_TRUE(fstat(fileCert, &st) == 0);
@@ -392,7 +413,9 @@ TEST(OpenSSLCompatibility, verifyOpenSslCertSign)
     close(fileCert);
 
      //open file
-    int fileKey = open("capub.der", O_RDONLY);
+    fpath = resolve_file_path("/capub.der");
+    int fileKey = open(fpath, O_RDONLY);
+    OICFree(fpath);
     ASSERT_TRUE(fileKey != -1);
     //get status
     ASSERT_TRUE(fstat(fileKey, &st) == 0);
@@ -415,13 +438,15 @@ TEST(OpenSSLCompatibility, verifyOpenSslCertSign)
 //test parsing of certificate chain generated by OpenSSL
 TEST(CertificateChain, LoadCertificateChain)
 {
+    char* fpath = NULL;
     ByteArray crtChainDer[MAX_CHAIN_LEN] = {{0,0},};
     CertificateX509 crtChain[MAX_CHAIN_LEN] = {{{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}},};
     ByteArray msg = BYTE_ARRAY_INITIALIZER;
     uint8_t chainLength;
 
-    FILE *file = fopen("cert_chain.dat", "rb");
-
+    fpath = resolve_file_path("/cert_chain.dat");
+    FILE *file = fopen(fpath, "rb");
+    OICFree(fpath);
     ASSERT_TRUE(file  != NULL);
 
     while (!feof (file))
@@ -445,6 +470,7 @@ TEST(CertificateChain, LoadCertificateChain)
 //test checking CA certificate generated by OpenSSL
 TEST(OpenSSLCompatibility, testOpenSSLCertificate)
 {
+    char* fpath = NULL;
     struct stat st;
     ByteArray crtDer = BYTE_ARRAY_INITIALIZER;
     uint8_t crtData[ISSUER_MAX_CERT_SIZE] = {0};
@@ -453,7 +479,9 @@ TEST(OpenSSLCompatibility, testOpenSSLCertificate)
     crtDer.len = sizeof(crtData);
 
     //open file
-    int fd = open("cacert.der", O_RDONLY);
+    fpath = resolve_file_path("/cacert.der");
+    int fd = open(fpath, O_RDONLY);
+    OICFree(fpath);
     ASSERT_TRUE(fd != -1);
     //get status
     ASSERT_TRUE(fstat(fd, &st) == 0);
@@ -481,8 +509,9 @@ TEST(OpenSSLCompatibility, ParseAndCheckCertificateChain)
     ByteArray msg = BYTE_ARRAY_INITIALIZER;
     uint8_t chainLength;
 
-    const char* chainPath = {"chain.der"};
+    char* chainPath = resolve_file_path("/chain.der");
     FILE *fileChain = fopen(chainPath, "rb");
+    OICFree(chainPath);
     ASSERT_TRUE(fileChain != NULL);
 
     //get the length
@@ -514,7 +543,9 @@ TEST(OpenSSLCompatibility, ParseAndCheckCertificateChain)
     caPubKey.len = sizeof(pubKeyData);
 
      //open file
-    int fileKey = open("capub.der", O_RDONLY);
+    char* fpath = resolve_file_path("/capub.der");
+    int fileKey = open(fpath, O_RDONLY);
+    OICFree(fpath);
     ASSERT_TRUE(fileKey != -1);
     //get status
     ASSERT_TRUE(fstat(fileKey, &st) == 0);
@@ -979,8 +1010,27 @@ TEST_F(PKITest, CRLSetGet)
 
     EXPECT_NE((void *)NULL, GetCrl());
     OICFree(defaultCrl);
+}
 
+//CKMGetCRL test
+TEST_F(PKITest, CKMGetCRL)
+{
+    const size_t CRL_MAX_SIZE = 1024;
+    ByteArray certificateRevocationList;
+    certificateRevocationList.data = (uint8_t*)OICCalloc(1,CRL_MAX_SIZE);
+    certificateRevocationList.len = CRL_MAX_SIZE;
+    EXPECT_EQ(PKI_SUCCESS, CKMGetCRL(&certificateRevocationList));
+    OICFree(certificateRevocationList.data);
+}
 
+//CKMSetCAInfo test
+TEST_F(PKITest, CKMSetCAInfo)
+{
+    ByteArray rootName = BYTE_ARRAY_INITIALIZER;
+    rootName.data = (uint8_t *)"ROOT2";
+    rootName.len = strlen((char *)rootName.data);
+    const long serNum = 100;
+    EXPECT_EQ(PKI_SUCCESS, CKMSetCAInfo(serNum, rootName));
 }
 
 int main(int argc, char **argv)
index 06454be..4cee10d 100644 (file)
Binary files a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat and b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat differ
index dbdee77..3de30a5 100644 (file)
@@ -8,32 +8,18 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
+                        },{\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
+                        },{\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/ad",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        } ,\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/cred",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.cred"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 7\r
@@ -94,6 +80,6 @@
         "deviceuuid": "61646d69-6e44-6576-6963-655555494430",\r
         "devowneruuid": "61646d69-6e44-6576-6963-655555494430",\r
         "rowneruuid": "61646d69-6e44-6576-6963-655555494430",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     }\r
 }
\ No newline at end of file
index 99fb37d..b87dd56 100644 (file)
 #include "ocstack.h"
 #include "securevirtualresourcetypes.h"
 
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
 /**
  * Function to generate credentials according to the type.
  *
index c6769e8..fe4e546 100644 (file)
@@ -41,7 +41,29 @@ extern "C"
  */
 OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
                                         OicSecAcl_t *acl, OCProvisionResultCB resultCallback);
-                                        
+
+/**
+ * API to request CRED information to resource.
+ *
+ * @param[in] selectedDeviceInfo Selected target device.
+ * @param[in] resultCallback callback provided by API user, callback will be called when
+ *            provisioning request recieves a response from resource server.
+ * @return OC_STACK_OK in case of success and other value otherwise.
+ */
+OCStackResult SRPGetCredResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
+        OCProvisionResultCB resultCallback);
+
+/**
+ * API to request ACL information to resource.
+ *
+ * @param[in] selectedDeviceInfo Selected target device.
+ * @param[in] resultCallback callback provided by API user, callback will be called when
+ *            provisioning request recieves a response from resource server.
+ * @return OC_STACK_OK in case of success and other value otherwise.
+ */
+OCStackResult SRPGetACLResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
+        OCProvisionResultCB resultCallback);
+
 #ifdef __WITH_X509__
 /**
  * API to send CRL information to resource.
index 986c360..155513e 100644 (file)
@@ -117,6 +117,30 @@ OCStackResult OCProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceIn
                              OCProvisionResultCB resultCallback);\r
 \r
 /**\r
+ * this function requests CRED information to resource.\r
+ *\r
+ * @param[in] ctx Application context would be returned in result callback.\r
+ * @param[in] selectedDeviceInfo Selected target device.\r
+ * @param[in] resultCallback callback provided by API user, callback will be called when provisioning\r
+              request recieves a response from resource server.\r
+ * @return  OC_STACK_OK in case of success and other value otherwise.\r
+ */\r
+OCStackResult OCGetCredResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,\r
+                             OCProvisionResultCB resultCallback);\r
+\r
+/**\r
+ * this function requests ACL information to resource.\r
+ *\r
+ * @param[in] ctx Application context would be returned in result callback.\r
+ * @param[in] selectedDeviceInfo Selected target device.\r
+ * @param[in] resultCallback callback provided by API user, callback will be called when provisioning\r
+              request recieves a response from resource server.\r
+ * @return  OC_STACK_OK in case of success and other value otherwise.\r
+ */\r
+OCStackResult OCGetACLResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,\r
+                             OCProvisionResultCB resultCallback);\r
+\r
+/**\r
  * this function sends Direct-Pairing Configuration to a device.\r
  *\r
  * @param[in] ctx Application context would be returned in result callback.\r
index eede02d..f6b7a7a 100644 (file)
@@ -111,11 +111,12 @@ typedef void (*OCProvisionResultCB)(void* ctx, int nOfRes, OCProvisionResult_t *
 /**
  * Callback function definition of direct-pairing
  *
+ * @param[OUT] ctx - User context which will be returned wth callback
  * @param[OUT] peer - pairing device info.
  * @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 (*OCDirectPairingResultCB)(OCDirectPairingDev_t *peer, OCStackResult result);
+typedef void (*OCDirectPairingResultCB)(void *ctx, OCDirectPairingDev_t *peer, OCStackResult result);
 
 
 #ifdef __cplusplus
index a4f645d..f4951ac 100644 (file)
@@ -20,6 +20,7 @@
 #
 
 Import('env')
+import os.path
 
 provisioning_env = env.Clone()
 
@@ -46,19 +47,30 @@ provisioning_env.AppendUnique(CPPPATH = [
                '../../../connectivity/api'
                ])
 
-provisioning_env.AppendUnique(CFLAGS = ['-D__WITH_DTLS__','-std=c99'])
-provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread', '-fpermissive'])
+target_os = env.get('TARGET_OS')
 provisioning_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
-provisioning_env.AppendUnique(LIBS = ['-lpthread','-ldl'])
-provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-provisioning_env.PrependUnique(LIBS = ['ocpmapi','oc', 'oc_logger', 'ocsrm','m', 'octbstack', 'connectivity_abstraction', 'coap'])
+provisioning_env.AppendUnique(CPPDEFINES = ['__WITH_DTLS__'])
+
+if target_os not in ['windows']:
+       provisioning_env.AppendUnique(CFLAGS = ['-std=c99'])
+       provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread', '-fpermissive'])
+       provisioning_env.AppendUnique(LIBS = ['-lpthread'])
+
+if target_os not in ['msys_nt', 'windows']:
+       provisioning_env.AppendUnique(LIBS = ['-ldl', 'm'])
+       provisioning_env.ParseConfig('pkg-config --libs glib-2.0');
+       provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+else:
+       provisioning_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk')])
+       provisioning_env.AppendUnique(LIBS = ['ws2_32', 'iphlpapi', 'advapi32', 'timer'])
+
+provisioning_env.PrependUnique(LIBS = ['ocpmapi','oc', 'oc_logger', 'ocsrm', 'octbstack', 'connectivity_abstraction', 'coap'])
 
 if env.get('SECURED') == '1':
     provisioning_env.AppendUnique(LIBS = ['tinydtls'])
 if env.get('DTLS_WITH_X509') == '1':
        provisioning_env.AppendUnique(LIBS = ['CKManager'])
        provisioning_env.AppendUnique(LIBS = ['asn1'])
-provisioning_env.ParseConfig('pkg-config --libs glib-2.0');
 
 provisioning_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 
index 781f654..62fd559 100644 (file)
Binary files a/resource/csdk/security/provisioning/sample/oic_svr_db_client.dat and b/resource/csdk/security/provisioning/sample/oic_svr_db_client.dat differ
index fb3c609..a8414b7 100644 (file)
@@ -8,38 +8,36 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
+                        },{\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
+                        },{\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
                         {\r
-                            "href": "/oic/ad",\r
+                            "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
-                            "href": "/oic/sec/amacl",\r
+                            "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                     "subjectuuid": "*",\r
                     "resources": [\r
                         {\r
-                            "href": "/oic/sec/doxm",\r
+                            "href": "/oic/sec/pconf",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pconf"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
-                            "href": "/oic/sec/pstat",\r
+                            "href": "/oic/sec/dpairing",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        }                  \r
+                            "rt": ["oic.r.dpairing"],\r
+                            "if": ["oic.if.baseline"]\r
+                        }\r
                     ],\r
                     "permission": 2\r
                 }\r
             ]\r
         },\r
         "rowneruuid" : "61646D69-6E44-6576-6963-655575696430"\r
-    },    \r
+    },\r
     "pstat": {\r
         "isop": true,\r
         "cm": 0,\r
@@ -81,7 +79,7 @@
         "sct": 1,\r
         "owned": true,\r
         "deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
-        "dpc": false,\r
+        "x.com.samsung.dpc": false,\r
         "devowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
         "rowneruuid": "61646D69-6E44-6576-6963-655575696430"\r
     }\r
index 3796ce7..b128c9c 100644 (file)
Binary files a/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.dat and b/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.dat differ
index 20f2c36..bd12a6d 100644 (file)
@@ -8,38 +8,18 @@
                         {
                             "href": "/oic/res",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
-                        },
-                        {
+                            "rt": ["oic.wk.res"],
+                            "if": ["oic.if.ll"]
+                        },{
                             "href": "/oic/d",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
-                        },
-                        {
+                            "rt": ["oic.wk.d"],
+                            "if": ["oic.if.baseline", "oic.if.r"]
+                        },{
                             "href": "/oic/p",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
-                        },
-                        {
-                            "href": "/oic/res/d",
-                            "rel": "",
-                            "rt": "",
-                            "if": ""
-                        },
-                        {
-                            "href": "/oic/res/types/d",
-                            "rel": "",
-                            "rt": "",
-                            "if": ""
-                        },
-                        {
-                            "href": "/oic/presence",
-                            "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.wk.p"],
+                            "if": ["oic.if.baseline", "oic.if.r"]
                         }
                     ],
                     "permission": 2
                         {
                             "href": "/oic/sec/doxm",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.doxm"],
+                            "if": ["oic.if.baseline"]
                         },
                         {
                             "href": "/oic/sec/pstat",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.pstat"],
+                            "if": ["oic.if.baseline"]
                         },
                         {
                             "href": "/oic/sec/acl",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.acl"],
+                            "if": ["oic.if.baseline"]
                         },
                         {
                             "href": "/oic/sec/cred",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.cred"],
+                            "if": ["oic.if.baseline"]
                         }
                     ],
                     "permission": 6
                         {
                             "href": "/oic/sec/pconf",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.pconf"],
+                            "if": ["oic.if.baseline"]
                         },
                         {
                             "href": "/oic/sec/dpairing",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.dpairing"],
+                            "if": ["oic.if.baseline"]
                         }
                     ],
                     "permission": 6
@@ -98,8 +78,8 @@
                         {
                             "href": "/oic/sec/ver",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.ver"],
+                            "if": ["oic.if.baseline"]
                         }
                     ],
                     "permission": 2
         "deviceuuid": "",
         "devowneruuid": "",
         "rowneruuid": "",
-        "dpc": true
+        "x.com.samsung.dpc": true
     }
 }
index 4adbf4d..08c7368 100644 (file)
Binary files a/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat and b/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat differ
old mode 100755 (executable)
new mode 100644 (file)
index 59b56a7..7809570
@@ -8,36 +8,18 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
                         },{\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },{\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/presence",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/cred",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.cred"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 6\r
                         {\r
                             "href": "/oic/sec/pconf",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pconf"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/dpairing",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.dpairing"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 6\r
@@ -96,8 +78,8 @@
                         {\r
                             "href": "/oic/sec/ver",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.ver"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
         "deviceuuid": "6A757374-776F-726B-4465-765575696430",\r
         "devowneruuid": "",\r
         "rowneruuid": "6A757374-776F-726B-4465-765575696430",\r
-        "dpc": true\r
+        "x.com.samsung.dpc": true\r
     }\r
-}
\ No newline at end of file
+}\r
index cfce7f8..bda680d 100644 (file)
Binary files a/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat and b/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat differ
index dc595bd..a316ced 100644 (file)
@@ -8,38 +8,18 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
+                        },{\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
+                        },{\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/presence",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/cred",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.cred"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 6\r
                         {\r
                             "href": "/oic/sec/pconf",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pconf"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/dpairing",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.dpairing"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 6\r
@@ -98,8 +78,8 @@
                         {\r
                             "href": "/oic/sec/ver",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.ver"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
         "deviceuuid": "72616E64-5069-6E44-6576-557569643030",\r
         "devowneruuid": "",\r
         "rowneruuid": "72616E64-5069-6E44-6576-557569643030",\r
-        "dpc": true\r
+        "x.com.samsung.dpc": true\r
     }\r
 }\r
index ab423b4..a22e393 100644 (file)
 
 #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"
 #include "oic_string.h"
@@ -50,9 +54,12 @@ extern "C"
 #define _34_CHECK_LINK_STATUS_  34
 #define _40_UNLINK_PAIR_DEVS_   40
 #define _50_REMOVE_SELEC_DEV_   50
+#define _60_GET_CRED_  60
+#define _61_GET_ACL_            61
 #define _99_EXIT_PRVN_CLT_      99
 
 #define ACL_RESRC_MAX_NUM   16
+#define ACL_RESRC_ARRAY_SIZE   3 //This value is used only for sample (not OCF spec)
 #define ACL_RESRC_MAX_LEN   128
 #define ACL_PEMISN_CNT      5
 #define DISCOVERY_TIMEOUT   10  // 10 sec
@@ -149,6 +156,34 @@ static void provisionAclCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool
     g_doneCB = true;
 }
 
+static void getCredCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
+{
+    if(!hasError)
+    {
+        OIC_LOG_V(INFO, TAG, "getCredCB SUCCEEDED - ctx: %s", (char*) ctx);
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "getCredCB FAILED - ctx: %s", (char*) ctx);
+        printResultList((const OCProvisionResult_t*) arr, nOfRes);
+    }
+    g_doneCB = true;
+}
+
+static void getAclCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
+{
+    if(!hasError)
+    {
+        OIC_LOG_V(INFO, TAG, "getAclCB SUCCEEDED - ctx: %s", (char*) ctx);
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "getAclCB FAILED - ctx: %s", (char*) ctx);
+        printResultList((const OCProvisionResult_t*) arr, nOfRes);
+    }
+    g_doneCB = true;
+}
+
 static void provisionDPCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
 {
     if(!hasError)
@@ -777,6 +812,125 @@ CKLST_ERROR:
     return -1;
 }
 
+static int getCred(void)
+{
+    // check |own_list| for checking selected link status on PRVN DB
+    if(!g_own_list || 1>g_own_cnt)
+    {
+        printf("   > Owned Device List, to Check Linked Status on PRVN DB, is Empty\n");
+        printf("   > Please Register Unowned Devices first, with [20] Menu\n");
+        return 0;  // normal case
+    }
+
+    // select device for checking selected link status on PRVN DB
+    int dev_num = 0;
+    for( ; ; )
+    {
+        printf("   > Enter Device Number, for Checking Linked Status on PRVN DB: ");
+        for(int ret=0; 1!=ret; )
+        {
+            ret = scanf("%d", &dev_num);
+            for( ; 0x20<=getchar(); );  // for removing overflow garbages
+                                        // '0x20<=code' is character region
+        }
+        if(0<dev_num && g_own_cnt>=dev_num)
+        {
+            break;
+        }
+        printf("     Entered Wrong Number. Please Enter Again\n");
+    }
+
+    // call |getDevInst| API actually
+    // calling this API with callback actually acts like blocking
+    // for error checking, the return value saved and printed
+    g_doneCB = false;
+    OCProvisionDev_t* dev = getDevInst((const OCProvisionDev_t*) g_own_list, dev_num);
+    if(!dev)
+    {
+        OIC_LOG(ERROR, TAG, "getDevInst: device instance empty");
+        goto PVACL_ERROR;
+    }
+    OCStackResult rst = OCGetCredResource((void*) g_ctx, dev, getCredCB);
+    if(OC_STACK_OK != rst)
+    {
+        OIC_LOG_V(ERROR, TAG, "OCGetCred API error: %d", rst);
+        goto PVACL_ERROR;
+    }
+    if(waitCallbackRet())  // input |g_doneCB| flag implicitly
+    {
+        OIC_LOG(ERROR, TAG, "OCGetCredResource callback error");
+        goto PVACL_ERROR;
+    }
+
+    // display the result of get credential
+    printf("   > Get Cred SUCCEEDED\n");
+
+    return 0;
+
+PVACL_ERROR:
+    return -1;
+}
+
+static int getAcl(void)
+{
+    // check |own_list| for checking selected link status on PRVN DB
+    if(!g_own_list || 1>g_own_cnt)
+    {
+        printf("   > Owned Device List, to Check Linked Status on PRVN DB, is Empty\n");
+        printf("   > Please Register Unowned Devices first, with [20] Menu\n");
+        return 0;  // normal case
+    }
+
+    // select device for checking selected link status on PRVN DB
+    int dev_num = 0;
+    for( ; ; )
+    {
+        printf("   > Enter Device Number, for Checking Linked Status on PRVN DB: ");
+        for(int ret=0; 1!=ret; )
+        {
+            ret = scanf("%d", &dev_num);
+            for( ; 0x20<=getchar(); );  // for removing overflow garbages
+                                        // '0x20<=code' is character region
+        }
+        if(0<dev_num && g_own_cnt>=dev_num)
+        {
+            break;
+        }
+        printf("     Entered Wrong Number. Please Enter Again\n");
+    }
+
+    // call |getDevInst| API actually
+    // calling this API with callback actually acts like blocking
+    // for error checking, the return value saved and printed
+    g_doneCB = false;
+    OCProvisionDev_t* dev = getDevInst((const OCProvisionDev_t*) g_own_list, dev_num);
+    if(!dev)
+    {
+        OIC_LOG(ERROR, TAG, "getDevInst: device instance empty");
+        goto PVACL_ERROR;
+    }
+    OCStackResult rst = OCGetACLResource((void*) g_ctx, dev, getAclCB);
+    if(OC_STACK_OK != rst)
+    {
+        OIC_LOG_V(ERROR, TAG, "OCGetACLResource API error: %d", rst);
+
+        goto PVACL_ERROR;
+    }
+    if(waitCallbackRet())  // input |g_doneCB| flag implicitly
+    {
+        OIC_LOG(ERROR, TAG, "OCGetACLResource callback error");
+        goto PVACL_ERROR;
+    }
+
+    // display the result of get credential
+    printf("   > Get ACL SUCCEEDED\n");
+
+    return 0;
+
+PVACL_ERROR:
+    return -1;
+}
+
 static int unlinkPairwise(void)
 {
     // check |own_list| for unlinking pairwise devices
@@ -893,6 +1047,13 @@ static OicSecAcl_t* createAcl(const int dev_num)
         OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
         return NULL;  // not need to 'goto' |ERROR| before allocating |acl|
     }
+    OicSecAce_t* ace = (OicSecAce_t*) OICCalloc(1, sizeof(OicSecAce_t));
+    if(!ace)
+    {
+        OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+        return NULL;  // not need to 'goto' |ERROR| before allocating |acl|
+    }
+    LL_APPEND(acl->aces, ace);
 
     // enter |subject| device number
     int num = 0;
@@ -918,7 +1079,7 @@ static OicSecAcl_t* createAcl(const int dev_num)
         OIC_LOG(ERROR, TAG, "createAcl: device instance empty");
         goto CRACL_ERROR;
     }
-    memcpy(&acl->subject, &dev->doxm->deviceID, UUID_LENGTH);
+    memcpy(&ace->subjectuuid, &dev->doxm->deviceID, UUID_LENGTH);
 
     // enter number of |resources| in 'accessed' device
     for( ; ; )
@@ -942,16 +1103,17 @@ static OicSecAcl_t* createAcl(const int dev_num)
     // enter actually each 'accessed' |resources| name
     printf("         Enter Each Accessed Resource Name (each under 128 char)\n");
             // '128' is ACL_RESRC_MAX_LEN
-    acl->resourcesLen = (unsigned) num;
-    acl->resources = (char**) OICCalloc(acl->resourcesLen, sizeof(char*));
-    if(!acl->resources)
-    {
-        OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
-        goto CRACL_ERROR;
-    }
+
     char rsrc_in[ACL_RESRC_MAX_LEN+1] = {0};  // '1' for null termination
-    for(int i=0; acl->resourcesLen>(unsigned)i; ++i)
+    for(int i = 0; num > i; ++i)
     {
+        OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+        if(!rsrc)
+        {
+            OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+            goto CRACL_ERROR;
+        }
+
         printf("         Enter Accessed Resource[%d] Name: ", i+1);
         for(int ret=0; 1!=ret; )
         {
@@ -960,14 +1122,98 @@ static OicSecAcl_t* createAcl(const int dev_num)
                                         // '0x20<=code' is character region
         }
         size_t len = strlen(rsrc_in)+1;  // '1' for null termination
-        char* rsrc = (char*) OICCalloc(len, sizeof(char));
+        rsrc->href = (char*) OICCalloc(len, sizeof(char));
         if(!rsrc)
         {
             OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
             goto CRACL_ERROR;
         }
-        OICStrcpy(rsrc, len, rsrc_in);
-        acl->resources[i] = rsrc;  // after here, |rsrc| points nothing
+        OICStrcpy(rsrc->href, len, rsrc_in);
+
+        int arrLen = 0;
+        while(1)
+        {
+            printf("         Enter Number of resource type for [%s]: ", rsrc_in);
+            for(int ret=0; 1!=ret; )
+            {
+                ret = scanf("%d", &arrLen);
+                for( ; 0x20<=getchar(); );  // for removing overflow garbages
+                                            // '0x20<=code' is character region
+            }
+            if(0 < arrLen && ACL_RESRC_ARRAY_SIZE >= arrLen)
+            {
+                break;
+            }
+            printf("     Entered Wrong Number. Please Enter under %d Again\n", ACL_RESRC_ARRAY_SIZE);
+        }
+
+        rsrc->typeLen = arrLen;
+        rsrc->types = (char**)OICCalloc(arrLen, sizeof(char*));
+        if(!rsrc->types)
+        {
+            OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+            goto CRACL_ERROR;
+        }
+
+        for(int i = 0; i < arrLen; i++)
+        {
+            printf("         Enter ResourceType[%d] Name: ", i+1);
+            for(int ret=0; 1!=ret; )
+            {
+                ret = scanf("%128s", rsrc_in);  // '128' is ACL_RESRC_MAX_LEN
+                for( ; 0x20<=getchar(); );  // for removing overflow garbages
+                                            // '0x20<=code' is character region
+            }
+            rsrc->types[i] = OICStrdup(rsrc_in);
+            if(!rsrc->types[i])
+            {
+                OIC_LOG(ERROR, TAG, "createAcl: OICStrdup error return");
+                goto CRACL_ERROR;
+            }
+        }
+
+        while(1)
+        {
+            printf("         Enter Number of interface name for [%s]: ", rsrc_in);
+            for(int ret=0; 1!=ret; )
+            {
+                ret = scanf("%d", &arrLen);
+                for( ; 0x20<=getchar(); );  // for removing overflow garbages
+                                            // '0x20<=code' is character region
+            }
+            if(0 < arrLen && ACL_RESRC_ARRAY_SIZE >= arrLen)
+            {
+                break;
+            }
+            printf("     Entered Wrong Number. Please Enter under %d Again\n", ACL_RESRC_ARRAY_SIZE);
+        }
+
+        rsrc->interfaceLen = arrLen;
+        rsrc->interfaces = (char**)OICCalloc(arrLen, sizeof(char*));
+        if(!rsrc->interfaces)
+        {
+            OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+            goto CRACL_ERROR;
+        }
+
+        for(int i = 0; i < arrLen; i++)
+        {
+            printf("         Enter ResourceType[%d] Name: ", i+1);
+            for(int ret=0; 1!=ret; )
+            {
+                ret = scanf("%128s", rsrc_in);  // '128' is ACL_RESRC_MAX_LEN
+                for( ; 0x20<=getchar(); );  // for removing overflow garbages
+                                            // '0x20<=code' is character region
+            }
+            rsrc->interfaces[i] = OICStrdup(rsrc_in);
+            if(!rsrc->interfaces[i])
+            {
+                OIC_LOG(ERROR, TAG, "createAcl: OICStrdup error return");
+                goto CRACL_ERROR;
+            }
+        }
+
+        LL_APPEND(ace->resources, rsrc);
     }
 
     // enter |permission| for this access
@@ -999,34 +1245,7 @@ static OicSecAcl_t* createAcl(const int dev_num)
         }
         pmsn_msk <<= 1;
     }
-    acl->permission = pmsn;
-
-    // enter |owner| device number
-    int own_num = 0;
-    for( ; ; )
-    {
-        printf("   > [D] Enter Owner Device Number: ");
-        for(int ret=0; 1!=ret; )
-        {
-            ret = scanf("%d", &own_num);
-            for( ; 0x20<=getchar(); );  // for removing overflow garbages
-                                        // '0x20<=code' is character region
-        }
-        if(0<own_num && g_own_cnt>=own_num)
-        {
-            break;
-        }
-        printf("         Entered Wrong Number. Please Enter Again\n");
-    }
-
-    dev = getDevInst((const OCProvisionDev_t*)g_own_list, own_num);
-    if(!dev || !dev->doxm)
-    {
-        OIC_LOG(ERROR, TAG, "createAcl: device instance empty");
-        goto CRACL_ERROR;
-    }
-    memcpy(&acl->rownerID, &dev->doxm->deviceID, sizeof(OicUuid_t));
-    printf("\n");
+    ace->permission = pmsn;
 
     return acl;
 
@@ -1212,7 +1431,7 @@ static int waitCallbackRet(void)
 
 static int selectTwoDiffNum(int* a, int* b, const int max, const char* str)
 {
-    if(!a || !b || 2>=max || !str)
+    if(!a || !b || 2>max || !str)
     {
         return -1;
     }
@@ -1275,6 +1494,10 @@ static void printMenu(void)
     printf("** [E] REMOVE THE SELECTED DEVICE\n");
     printf("** 50. Remove the Selected Device\n\n");
 
+    printf("** [F] GET SECURITY RESOURCE FOR DEBUGGING ONLY\n");
+    printf("** 60. Get the Credential resources of the Selected Device\n");
+    printf("** 61. Get the ACL resources of the Selected Device\n\n");
+
     printf("** [F] EXIT PROVISIONING CLIENT\n");
     printf("** 99. Exit Provisionong Client\n\n");
 
@@ -1393,6 +1616,18 @@ int main()
                 OIC_LOG(ERROR, TAG, "_50_REMOVE_SELEC_DEV_: error");
             }
             break;
+        case _60_GET_CRED_:
+            if(getCred())
+            {
+                OIC_LOG(ERROR, TAG, "_60_GET_CRED_: error");
+            }
+            break;
+        case _61_GET_ACL_:
+            if(getAcl())
+            {
+                OIC_LOG(ERROR, TAG, "_61_GET_ACL_: error");
+            }
+            break;
         case _99_EXIT_PRVN_CLT_:
             goto PMCLT_ERROR;
         default:
index 7047ae9..adec06f 100644 (file)
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#include <signal.h>
+#endif
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
+#endif
+#include <signal.h>
 #include "ocstack.h"
-#include "logger.h"
 #include "ocpayload.h"
+#include "pinoxmcommon.h"
+
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+/** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
+#ifdef ERROR
+#undef ERROR
+#endif //ERROR
+#endif //HAVE_WINDOWS_H
+#include "platform_features.h"
+#include "logger.h"
+
 
 #define TAG "SAMPLE_JUSTWORKS"
 
index 5ca0e7a..06a5512 100644 (file)
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#include <signal.h>
+#endif
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
+#endif
+#include <signal.h>
 #include "ocstack.h"
-#include "logger.h"
 #include "ocpayload.h"
 #include "pinoxmcommon.h"
 
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+/** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
+#ifdef ERROR
+#undef ERROR
+#endif //ERROR
+#endif //HAVE_WINDOWS_H
+#include "platform_features.h"
+#include "logger.h"
+
 #define TAG "SAMPLE_RANDOMPIN"
 
 int gQuitFlag = 0;
index 44e80a4..5062374 100644 (file)
@@ -44,8 +44,8 @@ OCStackResult PMGeneratePairWiseCredentials(OicSecCredType_t type, size_t keySiz
         const OicUuid_t *ptDeviceId, const OicUuid_t *firstDeviceId,
         const OicUuid_t *secondDeviceId, OicSecCred_t **firstCred, OicSecCred_t **secondCred)
 {
-    if (NULL == ptDeviceId || NULL == firstDeviceId || NULL != *firstCred || \
-        NULL == secondDeviceId || NULL != *secondCred)
+    if (NULL == ptDeviceId || NULL == firstDeviceId || NULL == firstCred || NULL != *firstCred || \
+        NULL == secondDeviceId || NULL == secondCred || NULL != *secondCred)
     {
         OIC_LOG(INFO, TAG, "Invalid params");
         return OC_STACK_INVALID_PARAM;
@@ -217,7 +217,7 @@ static OCStackResult GenerateCertificateAndKeys(const OicUuid_t * subject, OicSe
 OCStackResult PMGenerateCertificateCredentials(const OicUuid_t *ptDeviceId,
         const OicUuid_t *deviceId, OicSecCred_t **const cred)
 {
-    if (NULL == ptDeviceId || NULL == deviceId || NULL == cred)
+    if (NULL == ptDeviceId || NULL == deviceId || NULL == cred || NULL != *cred)
     {
         return OC_STACK_INVALID_PARAM;
     }
index b5d4bed..ad8133d 100644 (file)
@@ -163,6 +163,36 @@ OCStackResult OCProvisionACL(void* ctx, const OCProvisionDev_t *selectedDeviceIn
 }
 
 /**
+ * this function requests CRED information to resource.
+ *
+ * @param[in] ctx Application context would be returned in result callback.
+ * @param[in] selectedDeviceInfo Selected target device.
+ * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
+              request recieves a response from resource server.
+ * @return  OC_STACK_OK in case of success and other value otherwise.
+ */
+OCStackResult OCGetCredResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,
+                             OCProvisionResultCB resultCallback)
+{
+    return SRPGetCredResource(ctx, selectedDeviceInfo, resultCallback);
+}
+
+/**
+ * this function requests ACL information to resource.
+ *
+ * @param[in] ctx Application context would be returned in result callback.
+ * @param[in] selectedDeviceInfo Selected target device.
+ * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
+              request recieves a response from resource server.
+ * @return  OC_STACK_OK in case of success and other value otherwise.
+ */
+OCStackResult OCGetACLResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,
+                             OCProvisionResultCB resultCallback)
+{
+    return SRPGetACLResource(ctx, selectedDeviceInfo, resultCallback);
+}
+
+/**
  * function to provision credential to devices.
  *
  * @param[in] ctx Application context would be returned in result callback.
index 7b22d46..793525c 100644 (file)
 #define _POSIX_C_SOURCE 200809L
 #endif
 
+#ifdef HAVE_TIME_H
 #include <time.h>
+#endif
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
+#endif
 #include <stdbool.h>
 #include <string.h>
 
@@ -136,7 +142,7 @@ static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selecte
  * @param[in]  otmCtx  Context value of ownership transfer.
  * @return  OC_STACK_OK on success
  */
-static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx);
+static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx);
 
 /**
  * Function to send request to resource to get its pstat resource information.
@@ -154,7 +160,7 @@ static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx);
  * @param[in]  otmCtx  Context value of ownership transfer.
  * @return  OC_STACK_OK on success
  */
-static OCStackResult PutOwnerUuid(OTMContext_t* otmCtx);
+static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx);
 
 /**
  * Function to update the operation mode. As per the spec. Operation mode in client driven
@@ -163,7 +169,7 @@ static OCStackResult PutOwnerUuid(OTMContext_t* otmCtx);
  * @param[in]  otmCtx  Context value of ownership transfer.
  * @return  OC_STACK_OK on success
  */
-static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx);
+static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx);
 
 /**
  * Function to update the owner credential to new device
@@ -172,7 +178,7 @@ static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx);
  * @param[in] selectedOperationMode selected operation mode
  * @return  OC_STACK_OK on success
  */
-static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx);
+static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx);
 
 /**
  * Function to send ownerShip info.
@@ -181,7 +187,7 @@ static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx);
  * @param[in]  otmCtx  Context value of ownership transfer.
  * @return  OC_STACK_OK on success
  */
-static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx);
+static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx);
 
 /**
  * Function to update pstat as Ready for provisioning.
@@ -191,7 +197,7 @@ static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx);
  * @param[in] selectedDevice   selected device information to performing provisioning.
  * @return  OC_STACK_OK on success
  */
-static OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx);
+static OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx);
 
 /**
  * Function to update pstat as Ready for Normal Operation.
@@ -201,7 +207,7 @@ static OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx);
  * @param[in] selectedDevice   selected device information to performing provisioning.
  * @return  OC_STACK_OK on success
  */
-static OCStackResult PutNormalOperationStatus(OTMContext_t* otmCtx);
+static OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx);
 
 static bool IsComplete(OTMContext_t* otmCtx)
 {
@@ -315,8 +321,8 @@ void DTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
                    false == newDevDoxm->owned &&
                    memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) == 0)
                 {
-                    //Send request : PUT /oic/sec/doxm [{... , "devowner":"PT's UUID"}]
-                    res = PutOwnerUuid(g_otmCtx);
+                    //Send request : POST /oic/sec/doxm [{... , "devowner":"PT's UUID"}]
+                    res = PostOwnerUuid(g_otmCtx);
                     if(OC_STACK_OK != res)
                     {
                         OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to send owner information");
@@ -419,6 +425,28 @@ static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
                 &ownerKey, &ptDeviceID);
         VERIFY_NON_NULL(TAG, cred, ERROR);
 
+        // TODO: Added as workaround. Will be replaced soon.
+        cred->privateData.encoding = OIC_ENCODING_RAW;
+
+#if 1
+        // NOTE: Test codes to use BASE64 encoded owner PSK.
+        uint32_t outSize = 0;
+        size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((OWNER_PSK_LENGTH_128 + 1));
+        char* b64Buf = (uint8_t *)OICCalloc(1, b64BufSize);
+        VERIFY_NON_NULL(TAG, b64Buf, ERROR);
+        b64Encode(cred->privateData.data, cred->privateData.len, b64Buf, b64BufSize, &outSize);
+
+        OICFree( cred->privateData.data );
+        cred->privateData.data = (uint8_t *)OICCalloc(1, outSize + 1);
+        VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
+
+        strncpy(cred->privateData.data, b64Buf, outSize);
+        cred->privateData.data[outSize] = '\0';
+        cred->privateData.encoding = OIC_ENCODING_BASE64;
+        cred->privateData.len = outSize;
+        OICFree(b64Buf);
+#endif //End of Test codes
+
         res = AddCredential(cred);
         if(res != OC_STACK_OK)
         {
@@ -535,8 +563,8 @@ static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
         //Select operation mode (Currently supported SINGLE_SERVICE_CLIENT_DRIVEN only)
         SelectOperationMode(otmCtx->selectedDeviceInfo, &(otmCtx->selectedDeviceInfo->pstat->om));
 
-        //Send request : PUT /oic/sec/pstat [{"om":"bx11", .. }]
-        OCStackResult res = PutUpdateOperationMode(otmCtx);
+        //Send request : POST /oic/sec/pstat [{"om":"bx11", .. }]
+        OCStackResult res = PostUpdateOperationMode(otmCtx);
         if (OC_STACK_OK != res)
         {
             OIC_LOG(ERROR, TAG, "Error while updating operation mode.");
@@ -587,12 +615,12 @@ static OCStackApplicationResult OwnerUuidUpdateHandler(void *ctx, OCDoHandle UNU
                 return OC_STACK_DELETE_TRANSACTION;
             }
 
-            //PUT owner credential to new device according to security spec B.
-            res = PutOwnerCredential(otmCtx);
+            //POST owner credential to new device according to security spec B.
+            res = PostOwnerCredential(otmCtx);
             if(OC_STACK_OK != res)
             {
                 OIC_LOG(ERROR, TAG,
-                        "OwnerUuidUpdateHandler:Failed to send PUT request for onwer credential");
+                        "OwnerUuidUpdateHandler:Failed to send PosT request for onwer credential");
                 SetResult(otmCtx, res);
                 return OC_STACK_DELETE_TRANSACTION;
             }
@@ -738,11 +766,11 @@ static OCStackApplicationResult OwnerCredentialHandler(void *ctx, OCDoHandle UNU
                 }
             }
 
-            //PUT /oic/sec/doxm [{ ..., "owned":"TRUE" }]
-            res = PutOwnershipInformation(otmCtx);
+            //POST /oic/sec/doxm [{ ..., "owned":"TRUE" }]
+            res = PostOwnershipInformation(otmCtx);
             if(OC_STACK_OK != res)
             {
-                OIC_LOG(ERROR, TAG, "Failed to put ownership information to new device");
+                OIC_LOG(ERROR, TAG, "Failed to post ownership information to new device");
                 SetResult(otmCtx, res);
                 return OC_STACK_DELETE_TRANSACTION;
             }
@@ -789,7 +817,7 @@ static OCStackApplicationResult OwnershipInformationHandler(void *ctx, OCDoHandl
             OIC_LOG(INFO, TAG, "Ownership transfer was successfully completed.");
             OIC_LOG(INFO, TAG, "Set Ready for provisioning state .");
 
-            res = PutProvisioningStatus(otmCtx);
+            res = PostProvisioningStatus(otmCtx);
             if(OC_STACK_OK != res)
             {
                 OIC_LOG(ERROR, TAG, "Failed to update pstat");
@@ -837,7 +865,7 @@ static OCStackApplicationResult ProvisioningStatusHandler(void *ctx, OCDoHandle
         {
             OIC_LOG(INFO, TAG, "Device state is in Ready for Provisionig.");
 
-            res = PutNormalOperationStatus(otmCtx);
+            res = PostNormalOperationStatus(otmCtx);
             if(OC_STACK_OK != res)
             {
                 OIC_LOG(ERROR, TAG, "Failed to update pstat");
@@ -904,9 +932,9 @@ exit:
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx)
+static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx)
 {
-    OIC_LOG(DEBUG, TAG, "IN PutOwnerCredential");
+    OIC_LOG(DEBUG, TAG, "IN PostOwnerCredential");
 
     if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
@@ -922,7 +950,7 @@ static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx)
                         deviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_CRED_URI))
     {
-        OIC_LOG(ERROR, TAG, "PutOwnerCredential : Failed to generate query");
+        OIC_LOG(ERROR, TAG, "PostOwnerCredential : Failed to generate query");
         return OC_STACK_ERROR;
     }
     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
@@ -953,15 +981,17 @@ static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx)
         memcpy(&(newCredential.subject), &credSubjectId, sizeof(OicUuid_t));
 
         //Fill private data as empty string
-        newCredential.privateData.data = NULL;
+        newCredential.privateData.data = "";
         newCredential.privateData.len = 0;
+        newCredential.privateData.encoding = ownerCredential->privateData.encoding;
 #ifdef __WITH_X509__
         newCredential.publicData.data = NULL;
         newCredential.publicData.len = 0;
 #endif
-
-        //Send owner credential to new device : PUT /oic/sec/cred [ owner credential ]
-        if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData, &secPayload->payloadSize))
+        int secureFlag = 0;
+        //Send owner credential to new device : POST /oic/sec/cred [ owner credential ]
+        if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData,
+                                        &secPayload->payloadSize, secureFlag))
         {
             OICFree(secPayload);
             OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
@@ -974,9 +1004,9 @@ static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx)
         cbData.cb = &OwnerCredentialHandler;
         cbData.context = (void *)otmCtx;
         cbData.cd = NULL;
-        OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query,
+        OCStackResult res = OCDoResource(NULL, OC_REST_POST, query,
                                          &deviceInfo->endpoint, (OCPayload*)secPayload,
-                                         deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+                                         deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
         if (res != OC_STACK_OK)
         {
             OIC_LOG(ERROR, TAG, "OCStack resource error");
@@ -988,14 +1018,14 @@ static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx)
         return OC_STACK_NO_RESOURCE;
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT PutOwnerCredential");
+    OIC_LOG(DEBUG, TAG, "OUT PostOwnerCredential");
 
     return OC_STACK_OK;
 }
 
-static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx)
+static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx)
 {
-    OIC_LOG(DEBUG, TAG, "IN PutOwnerTransferModeToResource");
+    OIC_LOG(DEBUG, TAG, "IN PostOwnerTransferModeToResource");
 
     if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
@@ -1012,7 +1042,7 @@ static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx)
                         deviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_DOXM_URI))
     {
-        OIC_LOG(ERROR, TAG, "PutOwnerTransferModeToResource : Failed to generate query");
+        OIC_LOG(ERROR, TAG, "PostOwnerTransferModeToResource : Failed to generate query");
         return OC_STACK_ERROR;
     }
     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
@@ -1036,15 +1066,15 @@ static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx)
     cbData.cb = &OwnerTransferModeHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
-    res = OCDoResource(NULL, OC_REST_PUT, query,
+    res = OCDoResource(NULL, OC_REST_POST, query,
                        &deviceInfo->endpoint, (OCPayload *)secPayload,
-                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+                       deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
         OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT PutOwnerTransferModeToResource");
+    OIC_LOG(DEBUG, TAG, "OUT PostOwnerTransferModeToResource");
 
     return res;
 }
@@ -1076,7 +1106,7 @@ static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
     OCStackResult res = OCDoResource(NULL, OC_REST_GET, query, NULL, NULL,
-                                     deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+                                     deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
         OIC_LOG(ERROR, TAG, "OCStack resource error");
@@ -1087,9 +1117,9 @@ static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
     return res;
 }
 
-static OCStackResult PutOwnerUuid(OTMContext_t* otmCtx)
+static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx)
 {
-    OIC_LOG(DEBUG, TAG, "IN PutOwnerUuid");
+    OIC_LOG(DEBUG, TAG, "IN PostOwnerUuid");
 
     if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
@@ -1104,12 +1134,12 @@ static OCStackResult PutOwnerUuid(OTMContext_t* otmCtx)
                         deviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_DOXM_URI))
     {
-        OIC_LOG(ERROR, TAG, "PutOwnershipInformation : Failed to generate query");
+        OIC_LOG(ERROR, TAG, "PostOwnerUuid : Failed to generate query");
         return OC_STACK_ERROR;
     }
     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
 
-    //PUT PT's uuid to new device
+    //Post PT's uuid to new device
     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
     if(!secPayload)
     {
@@ -1132,21 +1162,21 @@ static OCStackResult PutOwnerUuid(OTMContext_t* otmCtx)
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
 
-    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload *)secPayload,
-            deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
+            deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
         OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT PutOwnerUuid");
+    OIC_LOG(DEBUG, TAG, "OUT PostOwnerUuid");
 
     return res;
 }
 
-static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx)
+static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx)
 {
-    OIC_LOG(DEBUG, TAG, "IN PutOwnershipInformation");
+    OIC_LOG(DEBUG, TAG, "IN PostOwnershipInformation");
 
     if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
@@ -1161,7 +1191,7 @@ static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx)
                         deviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_DOXM_URI))
     {
-        OIC_LOG(ERROR, TAG, "PutOwnershipInformation : Failed to generate query");
+        OIC_LOG(ERROR, TAG, "PostOwnershipInformation : Failed to generate query");
         return OC_STACK_ERROR;
     }
     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
@@ -1191,21 +1221,21 @@ static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx)
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
 
-    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
-                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
+                       deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
         OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT PutOwnershipInformation");
+    OIC_LOG(DEBUG, TAG, "OUT PostOwnershipInformation");
 
     return res;
 }
 
-static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx)
+static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx)
 {
-    OIC_LOG(DEBUG, TAG, "IN PutUpdateOperationMode");
+    OIC_LOG(DEBUG, TAG, "IN PostUpdateOperationMode");
 
     if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
@@ -1219,7 +1249,7 @@ static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx)
                         deviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
     {
-        OIC_LOG(ERROR, TAG, "PutUpdateOperationMode : Failed to generate query");
+        OIC_LOG(ERROR, TAG, "PostUpdateOperationMode : Failed to generate query");
         return OC_STACK_ERROR;
     }
     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
@@ -1244,14 +1274,14 @@ static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx)
     cbData.cb = &OperationModeUpdateHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
-    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload *)secPayload,
-                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
+                       deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
         OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
 
-    OIC_LOG(DEBUG, TAG, "OUT PutUpdateOperationMode");
+    OIC_LOG(DEBUG, TAG, "OUT PostUpdateOperationMode");
 
     return res;
 }
@@ -1274,8 +1304,8 @@ static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selecte
     }
     OIC_LOG_V(DEBUG, TAG, "Selected provisoning method = %d", selectedDevice->doxm->oxmSel);
 
-    //Send Req: PUT /oic/sec/doxm [{..."OxmSel" :g_OTMDatas[Index of Selected OxM].OXMString,...}]
-    res = PutOwnerTransferModeToResource(otmCtx);
+    //Send Req: POST /oic/sec/doxm [{..."OxmSel" :g_OTMDatas[Index of Selected OxM].OXMString,...}]
+    res = PostOwnerTransferModeToResource(otmCtx);
     if(OC_STACK_OK != res)
     {
         OIC_LOG(WARNING, TAG, "Failed to select the provisioning method");
@@ -1402,9 +1432,9 @@ error:
     return res;
 }
 
-OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
+OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx)
 {
-    OIC_LOG(INFO, TAG, "IN PutProvisioningStatus");
+    OIC_LOG(INFO, TAG, "IN PostProvisioningStatus");
 
     if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
@@ -1438,7 +1468,7 @@ OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
                         otmCtx->selectedDeviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
     {
-        OIC_LOG(ERROR, TAG, "PutProvisioningStatus : Failed to generate query");
+        OIC_LOG(ERROR, TAG, "PostProvisioningStatus : Failed to generate query");
         return OC_STACK_ERROR;
     }
     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
@@ -1447,7 +1477,7 @@ OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
     cbData.cb = &ProvisioningStatusHandler;
     cbData.context = (void*)otmCtx;
     cbData.cd = NULL;
-    OCStackResult ret = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
+    OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
             otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
     OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
     if (ret != OC_STACK_OK)
@@ -1455,14 +1485,14 @@ OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
         OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
 
-    OIC_LOG(INFO, TAG, "OUT PutProvisioningStatus");
+    OIC_LOG(INFO, TAG, "OUT PostProvisioningStatus");
 
     return ret;
 }
 
-OCStackResult PutNormalOperationStatus(OTMContext_t* otmCtx)
+OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx)
 {
-    OIC_LOG(INFO, TAG, "IN PutNormalOperationStatus");
+    OIC_LOG(INFO, TAG, "IN PostNormalOperationStatus");
 
     if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
@@ -1496,7 +1526,7 @@ OCStackResult PutNormalOperationStatus(OTMContext_t* otmCtx)
                         otmCtx->selectedDeviceInfo->connType,
                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
     {
-        OIC_LOG(ERROR, TAG, "PutNormalOperationStatus : Failed to generate query");
+        OIC_LOG(ERROR, TAG, "PostNormalOperationStatus : Failed to generate query");
         return OC_STACK_ERROR;
     }
     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
@@ -1505,7 +1535,7 @@ OCStackResult PutNormalOperationStatus(OTMContext_t* otmCtx)
     cbData.cb = &ReadyForNomalStatusHandler;
     cbData.context = (void*)otmCtx;
     cbData.cd = NULL;
-    OCStackResult ret = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
+    OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
             otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
     OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
     if (ret != OC_STACK_OK)
@@ -1513,7 +1543,7 @@ OCStackResult PutNormalOperationStatus(OTMContext_t* otmCtx)
         OIC_LOG(ERROR, TAG, "OCStack resource error");
     }
 
-    OIC_LOG(INFO, TAG, "OUT PutNormalOperationStatus");
+    OIC_LOG(INFO, TAG, "OUT PostNormalOperationStatus");
 
     return ret;
 }
index e55e9a6..b72c28c 100644 (file)
 #define _POSIX_C_SOURCE 200112L
 #endif
 
+#if HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_STRING_H
 #include <string.h>
-#include <time.h>
-#include <sys/time.h>
+#endif
 
 #include "ocstack.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
+#include "oic_time.h"
 #include "logger.h"
 #include "cJSON.h"
 #include "utlist.h"
@@ -341,31 +344,14 @@ exit:
  */
 OCStackResult PMTimeout(unsigned short waittime, bool waitForStackResponse)
 {
-    struct timespec startTime = {.tv_sec=0, .tv_nsec=0};
-    struct timespec currTime  = {.tv_sec=0, .tv_nsec=0};
-
     OCStackResult res = OC_STACK_OK;
-#ifdef _POSIX_MONOTONIC_CLOCK
-    int clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);
-#else
-    int clock_res = clock_gettime(CLOCK_REALTIME, &startTime);
-#endif
-    if (0 != clock_res)
-    {
-        return OC_STACK_ERROR;
-    }
+
+    uint64_t startTime = OICGetCurrentTime(TIME_IN_MS);
     while (OC_STACK_OK == res)
     {
-#ifdef _POSIX_MONOTONIC_CLOCK
-        clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
-#else
-        clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
-#endif
-        if (0 != clock_res)
-        {
-            return OC_STACK_TIMEOUT;
-        }
-        long elapsed = (currTime.tv_sec - startTime.tv_sec);
+        uint64_t currTime = OICGetCurrentTime(TIME_IN_MS);
+
+        long elapsed = (long)((currTime - startTime) / MS_PER_SEC);
         if (elapsed > waittime)
         {
             return OC_STACK_OK;
@@ -428,8 +414,8 @@ uint16_t GetSecurePortFromJSON(char* jsonStr)
 }
 
 bool PMGenerateQuery(bool isSecure,
-                     const char* address, const uint16_t port,
-                     const OCConnectivityType connType,
+                     const char* address, uint16_t port,
+                     OCConnectivityType connType,
                      char* buffer, size_t bufferSize, const char* uri)
 {
     if(!address || !buffer || !uri)
@@ -584,6 +570,25 @@ static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle
             uint16_t securePort = 0;
             OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
 
+            // Use seure port of doxm for OTM and Provision.
+            while (resPayload)
+            {
+                if (0 == strncmp(resPayload->uri, OIC_RSRC_DOXM_URI, strlen(OIC_RSRC_DOXM_URI)))
+                {
+                    OIC_LOG_V(INFO,TAG,"resPaylod->uri:%s",resPayload->uri);
+                    OIC_LOG(INFO, TAG, "Found doxm resource.");
+                    break;
+                }
+                else
+                {
+                    resPayload = resPayload->next;
+                }
+            }
+            if (NULL == resPayload)
+            {
+                OIC_LOG(ERROR, TAG, "Can not find doxm resource.");
+                return OC_STACK_DELETE_TRANSACTION;
+            }
             if (resPayload && resPayload->secure)
             {
                 securePort = resPayload->port;
@@ -691,6 +696,22 @@ static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNU
                     return OC_STACK_KEEP_TRANSACTION;
                 }
 
+                res = GetDoxmDeviceID(&myId);
+                if(OC_STACK_OK != res)
+                {
+                    OIC_LOG(ERROR, TAG, "Error while getting my UUID.");
+                    DeleteDoxmBinData(ptrDoxm);
+                    return OC_STACK_KEEP_TRANSACTION;
+                }
+                //if this is owned discovery and this is PT's reply, discard it
+                if((pDInfo->isOwnedDiscovery) &&
+                        (0 == memcmp(&ptrDoxm->deviceID.id, &myId.id, sizeof(myId.id))) )
+                {
+                    OIC_LOG(DEBUG, TAG, "discarding provision tool's reply");
+                    DeleteDoxmBinData(ptrDoxm);
+                    return OC_STACK_KEEP_TRANSACTION;
+                }
+
                 res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
                         clientResponse->devAddr.port,
                         clientResponse->devAddr.adapter,
@@ -768,7 +789,7 @@ OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisi
 
     OCDoHandle handle = NULL;
     res = OCDoResource(&handle, OC_REST_DISCOVER, query, 0, 0,
-                                     CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
+                                     CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
         OIC_LOG(ERROR, TAG, "OCStack resource error");
@@ -782,14 +803,14 @@ OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisi
     {
         OIC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
         OICFree(pDInfo);
-        OCStackResult resCancel = OCCancel(handle, OC_LOW_QOS, NULL, 0);
+        OCStackResult resCancel = OCCancel(handle, OC_HIGH_QOS, NULL, 0);
         if(OC_STACK_OK !=  resCancel)
         {
             OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
         }
         return res;
     }
-    res = OCCancel(handle,OC_LOW_QOS,NULL,0);
+    res = OCCancel(handle,OC_HIGH_QOS,NULL,0);
     if (OC_STACK_OK != res)
     {
         OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
@@ -810,21 +831,12 @@ static OCStackResult SecurePortDiscovery(DiscoveryInfo* discoveryInfo,
     {
         return OC_STACK_INVALID_PARAM;
     }
-
-    char rsrc_uri[MAX_URI_LENGTH+1] = {0};
-    int wr_len = snprintf(rsrc_uri, sizeof(rsrc_uri), "%s?%s=%s",
-              OC_RSRVD_WELL_KNOWN_URI, OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DOXM);
-    if(wr_len <= 0 || (size_t)wr_len >= sizeof(rsrc_uri))
-    {
-        OIC_LOG(ERROR, TAG, "rsrc_uri_string_print failed");
-        return OC_STACK_ERROR;
-    }
     //Try to the unicast discovery to getting secure port
     char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
     if(!PMGenerateQuery(false,
                         clientResponse->devAddr.addr, clientResponse->devAddr.port,
                         clientResponse->connType,
-                        query, sizeof(query), rsrc_uri))
+                        query, sizeof(query), OC_RSRVD_WELL_KNOWN_URI))
     {
         OIC_LOG(ERROR, TAG, "SecurePortDiscovery : Failed to generate query");
         return OC_STACK_ERROR;
@@ -836,7 +848,7 @@ static OCStackResult SecurePortDiscovery(DiscoveryInfo* discoveryInfo,
     cbData.context = (void*)discoveryInfo;
     cbData.cd = NULL;
     OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
-            clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0);
+            clientResponse->connType, OC_HIGH_QOS, &cbData, NULL, 0);
     if(OC_STACK_OK != ret)
     {
         OIC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
@@ -879,7 +891,7 @@ static OCStackResult SecurityVersionDiscovery(DiscoveryInfo* discoveryInfo,
     cbData.context = (void*)discoveryInfo;
     cbData.cd = NULL;
     OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
-            clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0);
+            clientResponse->connType, OC_HIGH_QOS, &cbData, NULL, 0);
     if(OC_STACK_OK != ret)
     {
         OIC_LOG(ERROR, TAG, "Failed to Security Version Discovery");
index 9799ea4..35aebec 100644 (file)
@@ -20,7 +20,9 @@
 #include <stdio.h>
 #include <string.h>
 #include <stdint.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 
 #include "ocprovisioningmanager.h"
 #include "secureresourceprovider.h"
@@ -91,6 +93,16 @@ struct ACLData
     int numOfResults;                           /**< Number of results in result array.**/
 };
 
+// Structure to carry get security resource APIs data to callback.
+typedef struct GetSecData GetSecData_t;
+struct GetSecData {
+    void *ctx;
+    const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
+    OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
+    OCProvisionResult_t *resArr;                /**< Result array.**/
+    int numOfResults;                        /**< Number of results in result array.**/
+};
+
 /**
  * Structure to carry PCONF provision API data to callback.
  */
@@ -304,7 +316,9 @@ static OCStackResult provisionCredentials(const OicSecCred_t *cred,
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData, &secPayload->payloadSize);
+    int secureFlag = 0;
+    OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData,
+                                          &secPayload->payloadSize, secureFlag);
     if((OC_STACK_OK != res) && (NULL == secPayload->securityData))
     {
         OCPayloadDestroy((OCPayload *)secPayload);
@@ -541,8 +555,9 @@ static OCStackResult provisionCertCred(const OicSecCred_t *cred,
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
+    int secureFlag = 0;
     OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData,
-        &secPayload->payloadSize);
+        &secPayload->payloadSize, secureFlag);
 
     if ((OC_STACK_OK != res) || (NULL == secPayload->securityData))
     {
@@ -865,6 +880,9 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
         OIC_LOG(ERROR, TAG, "Failed to AclToCBORPayload");
         return OC_STACK_NO_MEMORY;
     }
+    OIC_LOG(DEBUG, TAG, "Created payload for ACL:");
+    OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
+
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
                         selectedDeviceInfo->endpoint.addr,
@@ -1055,7 +1073,7 @@ OCStackResult SRPProvisionDirectPairing(void *ctx, const OCProvisionDev_t *selec
     OIC_LOG(DEBUG, TAG, "Sending PCONF info to resource server");
     OCStackResult ret = OCDoResource(&handle, method, query,
             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
-            selectedDeviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+            selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
     if (OC_STACK_OK != ret)
     {
         OICFree(pconfData->resArr);
@@ -1709,3 +1727,245 @@ error:
     OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDevice");
     return res;
 }
+
+/**
+ * Internal Function to store results in result array during GetCredResourceCB.
+ */
+static void registerResultForGetCredResourceCB(GetSecData_t *GetSecData,
+                                             OCStackResult stackresult)
+{
+   OIC_LOG_V(INFO, TAG, "Inside registerResultForGetCredResourceCB "
+           "GetSecData->numOfResults is %d\n", GetSecData->numOfResults);
+   memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
+          GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
+   GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
+   ++(GetSecData->numOfResults);
+}
+
+/**
+ * Callback handler of SRPGetCredResource.
+ *
+ * @param[in] ctx             ctx value passed to callback from calling function.
+ * @param[in] UNUSED          handle to an invocation
+ * @param[in] clientResponse  Response from queries to remote servers.
+ * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
+ *          and  OC_STACK_KEEP_TRANSACTION to keep it.
+ */
+static OCStackApplicationResult SRPGetCredResourceCB(void *ctx, OCDoHandle UNUSED,
+                                                  OCClientResponse *clientResponse)
+{
+    OIC_LOG_V(INFO, TAG, "Inside SRPGetCredResourceCB.");
+    (void)UNUSED;
+    VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
+    GetSecData_t *GetSecData = (GetSecData_t*)ctx;
+    OCProvisionResultCB resultCallback = GetSecData->resultCallback;
+
+    if (clientResponse)
+    {
+        if(OC_STACK_OK == clientResponse->result)
+        {
+            uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
+            size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
+
+            OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
+
+            registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
+            ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
+                                                    GetSecData->resArr,
+                                                    false);
+             OICFree(GetSecData->resArr);
+             OICFree(GetSecData);
+
+            return OC_STACK_DELETE_TRANSACTION;
+        }
+    }
+    registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
+    ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
+                                            GetSecData->resArr,
+                                            false);
+    OIC_LOG_V(ERROR, TAG, "SRPGetCredResourceCB received Null clientResponse");
+    OICFree(GetSecData->resArr);
+    OICFree(GetSecData);
+
+    return OC_STACK_DELETE_TRANSACTION;
+}
+
+
+OCStackResult SRPGetCredResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
+        OCProvisionResultCB resultCallback)
+{
+    VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
+
+    char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
+    if(!PMGenerateQuery(true,
+                        selectedDeviceInfo->endpoint.addr,
+                        selectedDeviceInfo->securePort,
+                        selectedDeviceInfo->connType,
+                        query, sizeof(query), OIC_RSRC_CRED_URI))
+    {
+        OIC_LOG(ERROR, TAG, "SRPGetCredResource : Failed to generate query");
+        return OC_STACK_ERROR;
+    }
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
+
+    OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
+    cbData.cb = &SRPGetCredResourceCB;
+    GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
+    if (NULL == GetSecData)
+    {
+        OIC_LOG(ERROR, TAG, "Unable to allocate memory");
+        return OC_STACK_NO_MEMORY;
+    }
+    GetSecData->deviceInfo = selectedDeviceInfo;
+    GetSecData->resultCallback = resultCallback;
+    GetSecData->numOfResults=0;
+    GetSecData->ctx = ctx;
+
+    int noOfRiCalls = 1;
+    GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
+    if (NULL == GetSecData->resArr)
+    {
+        OICFree(GetSecData);
+        OIC_LOG(ERROR, TAG, "Unable to allocate memory");
+        return OC_STACK_NO_MEMORY;
+    }
+    cbData.context = (void *)GetSecData;
+    cbData.cd = NULL;
+    OCMethod method = OC_REST_GET;
+    OCDoHandle handle = NULL;
+    OIC_LOG(DEBUG, TAG, "Sending Get Cred to  resource server");
+    OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
+            selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
+    if (OC_STACK_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
+        OICFree(GetSecData->resArr);
+        OICFree(GetSecData);
+    }
+    VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
+    OIC_LOG(DEBUG, TAG, "OUT SRPGetCredResource");
+
+    return OC_STACK_OK;
+}
+
+/**
+ * Internal Function to store results in result array during GetACLResourceCB.
+ */
+static void registerResultForGetACLResourceCB(GetSecData_t *GetSecData,
+                                             OCStackResult stackresult)
+{
+   OIC_LOG_V(INFO, TAG, "Inside registerResultForGetACLResourceCB "
+           "GetSecData->numOfResults is %d\n", GetSecData->numOfResults);
+   memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
+          GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
+   GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
+   ++(GetSecData->numOfResults);
+}
+
+/**
+ * Callback handler of SRPGetACLResource.
+ *
+ * @param[in] ctx             ctx value passed to callback from calling function.
+ * @param[in] UNUSED          handle to an invocation
+ * @param[in] clientResponse  Response from queries to remote servers.
+ * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
+ *          and  OC_STACK_KEEP_TRANSACTION to keep it.
+ */
+static OCStackApplicationResult SRPGetACLResourceCB(void *ctx, OCDoHandle UNUSED,
+                                                  OCClientResponse *clientResponse)
+{
+    OIC_LOG_V(INFO, TAG, "Inside SRPGetACLResourceCB.");
+    (void)UNUSED;
+    VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
+    GetSecData_t *GetSecData = (GetSecData_t*)ctx;
+    OCProvisionResultCB resultCallback = GetSecData->resultCallback;
+
+    if (clientResponse)
+    {
+        if(OC_STACK_OK == clientResponse->result)
+        {
+            uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
+            size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
+
+            OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
+
+            registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
+            ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
+                                                    GetSecData->resArr,
+                                                    false);
+             OICFree(GetSecData->resArr);
+             OICFree(GetSecData);
+
+            return OC_STACK_DELETE_TRANSACTION;
+        }
+    }
+    registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
+    ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
+                                            GetSecData->resArr,
+                                            false);
+    OIC_LOG_V(ERROR, TAG, "SRPGetACLResourceCB received Null clientResponse");
+    OICFree(GetSecData->resArr);
+    OICFree(GetSecData);
+
+    return OC_STACK_DELETE_TRANSACTION;
+}
+
+
+OCStackResult SRPGetACLResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
+        OCProvisionResultCB resultCallback)
+{
+    VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
+
+    char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
+    if(!PMGenerateQuery(true,
+                        selectedDeviceInfo->endpoint.addr,
+                        selectedDeviceInfo->securePort,
+                        selectedDeviceInfo->connType,
+                        query, sizeof(query), OIC_RSRC_ACL_URI))
+    {
+        OIC_LOG(ERROR, TAG, "SRPGetACLResource : Failed to generate query");
+        return OC_STACK_ERROR;
+    }
+    OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
+
+    OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
+    cbData.cb = &SRPGetACLResourceCB;
+    GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
+    if (NULL == GetSecData)
+    {
+        OIC_LOG(ERROR, TAG, "Unable to allocate memory");
+        return OC_STACK_NO_MEMORY;
+    }
+    GetSecData->deviceInfo = selectedDeviceInfo;
+    GetSecData->resultCallback = resultCallback;
+    GetSecData->numOfResults=0;
+    GetSecData->ctx = ctx;
+
+    int noOfRiCalls = 1;
+    GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
+    if (NULL == GetSecData->resArr)
+    {
+        OICFree(GetSecData);
+        OIC_LOG(ERROR, TAG, "Unable to allocate memory");
+        return OC_STACK_NO_MEMORY;
+    }
+    cbData.context = (void *)GetSecData;
+    cbData.cd = NULL;
+    OCMethod method = OC_REST_GET;
+    OCDoHandle handle = NULL;
+    OIC_LOG(DEBUG, TAG, "Sending Get ACL to resource server");
+    OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
+            selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
+    if (OC_STACK_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "OCStack resource error");
+        OICFree(GetSecData->resArr);
+        OICFree(GetSecData);
+    }
+    VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
+    OIC_LOG(DEBUG, TAG, "OUT SRPGetACLResource");
+
+    return OC_STACK_OK;
+}
index ee406d5..7c36b06 100644 (file)
@@ -25,23 +25,33 @@ import os.path
 sptest_env = env.Clone()
 
 src_dir = sptest_env.get('SRC_DIR')
+target_os = env.get('TARGET_OS')
 
 ######################################################################
 # Build flags
 ######################################################################
 sptest_env.PrependUnique(CPPPATH = [
-               '../../../connectivity/inc',
-               '../../../connectivity/api',
+               '../include',
                '../../include',
-               '../../../../../extlibs/tinydtls',
                '../include/internal',
-               '../include/oxm',
+               '../../../stack/include',
+               '../../../ocrandom/include',
                '../../../logger/include',
                '../../../stack/include',
+               '../../../security/include',
+               '../../../security/include/internal',
+               '../../../security/provisioning/include/internal',
                '../../../../oc_logger/include',
-               '../../../../../extlibs/gtest/gtest-1.7.0/include',
-               '../include',
-               '../include/internal'
+               '../include/oxm',
+               '../../../../../extlibs/tinydtls',
+               '../../../../../extlibs/cjson',
+               '../../../../../extlibs/base64',
+               '../../../connectivity/inc',
+               '../../../connectivity/common/inc',
+               '../../../connectivity/lib/libcoap-4.1.1',
+               '../../../connectivity/api',
+               '../../../../../extlibs/tinydtls',
+               '../../../../../extlibs/gtest/gtest-1.7.0/include'
                ])
 sptest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
 sptest_env.AppendUnique(LIBS = ['-lpthread','-ldl'])
@@ -58,6 +68,7 @@ sptest_env.PrependUnique(LIBS = [   'ocpmapi',
                                     'gtest_main'])
 
 if env.get('SECURED') == '1':
+    sptest_env.AppendUnique(LIBS = ['timer'])
     sptest_env.AppendUnique(LIBS = ['tinydtls'])
 if env.get('DTLS_WITH_X509') == '1':
        sptest_env.AppendUnique(LIBS = ['CKManager'])
@@ -66,26 +77,44 @@ if env.get('DTLS_WITH_X509') == '1':
 if not 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'])
+
 ######################################################################
 # Source files and Targets
 ######################################################################
-unittest = sptest_env.Program('unittest', ['pmutilitytest.cpp', 'otmunittest.cpp',
-                                           'secureresourceprovider.cpp',
-                                           'provisioningdatabasemanager.cpp',
-                                           'ocprovisioningmanager.cpp' ])
+unittest_src = ['pmutilitytest.cpp',
+                'secureresourceprovider.cpp',
+                'provisioningdatabasemanager.cpp',
+                'ocprovisioningmanager.cpp',
+                'credentialgeneratortest.cpp',
+                ]
+
+if target_os not in ['windows']:
+    unittest_src += [ 'otmunittest.cpp' ]
+
+unittest = sptest_env.Program('unittest', unittest_src)
+
+if target_os not in ['windows']:
+    sample_server1 = sptest_env.Program('sample_server1', ['sampleserver1.cpp'])
+    sample_server2 = sptest_env.Program('sample_server2', ['sampleserver2.cpp'])
+    Alias("test", [sample_server1, sample_server2])
 
 Alias("test", [unittest])
 
 env.AppendTarget('test')
 if env.get('TEST') == '1':
-       target_os = env.get('TARGET_OS')
-       if target_os == 'linux':
+       if target_os in ['linux', 'windows']:
                out_dir = env.get('BUILD_DIR')
                result_dir = env.get('BUILD_DIR') + '/test_out/'
                if not os.path.isdir(result_dir):
                        os.makedirs(result_dir)
                sptest_env.AppendENVPath('GTEST_OUTPUT', ['xml:'+ result_dir])
                sptest_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir])
+               sptest_env.AppendENVPath('PATH', env.get('BUILD_DIR'))
                sptest_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
                ut = sptest_env.Command ('ut', None, out_dir + '/resource/csdk/security/provisioning/unittest/unittest')
                AlwaysBuild ('ut')
diff --git a/resource/csdk/security/provisioning/unittest/credentialgeneratortest.cpp b/resource/csdk/security/provisioning/unittest/credentialgeneratortest.cpp
new file mode 100644 (file)
index 0000000..52a034b
--- /dev/null
@@ -0,0 +1,159 @@
+/* *****************************************************************
+ *
+ * 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 "gtest/gtest.h"
+#include "credentialgenerator.h"
+#include "oic_malloc.h"
+
+
+TEST(PMGeneratePairWiseCredentialsTest, InvalidProvisioningtoolDevID)
+{
+    OicUuid_t *firstDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+    if(firstDevID)
+    {
+        firstDevID->id[0] = 1;
+    }
+    OicUuid_t *SecondDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+    if(SecondDevID)
+    {
+        SecondDevID->id[0] = 2;
+    }
+    OicSecCred_t *cred1 = NULL;
+    OicSecCred_t *cred2 = NULL;
+    size_t keySize = OWNER_PSK_LENGTH_128;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGeneratePairWiseCredentials(NO_SECURITY_MODE,
+             keySize, NULL, firstDevID, SecondDevID, &cred1, &cred2));
+    OICFree(firstDevID);
+    OICFree(SecondDevID);
+}
+
+TEST(PMGeneratePairWiseCredentialsTest, InvalidFirstDevID)
+{
+    OicUuid_t *SecondDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+    if(SecondDevID)
+    {
+        SecondDevID->id[0] = 2;
+    }
+    OicUuid_t *provisioningDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+    if(provisioningDevID)
+    {
+        provisioningDevID->id[0] = 1;
+    }
+    OicSecCred_t *cred1 = NULL;
+    OicSecCred_t *cred2 = NULL;
+    size_t keySize = OWNER_PSK_LENGTH_128;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGeneratePairWiseCredentials(NO_SECURITY_MODE,
+              keySize, provisioningDevID, NULL, SecondDevID, &cred1, &cred2));
+    OICFree(SecondDevID);
+    OICFree(provisioningDevID);
+}
+
+TEST(PMGeneratePairWiseCredentialsTest, InvalidSecondDevID)
+{
+    OicUuid_t *firstDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+    if(firstDevID)
+    {
+        firstDevID->id[0] = 1;
+    }
+    OicUuid_t *provisioningDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+    if(provisioningDevID)
+    {
+        provisioningDevID->id[0] = 2;
+    }
+    OicSecCred_t *cred1 = NULL;
+    OicSecCred_t *cred2 = NULL;
+    size_t keySize = OWNER_PSK_LENGTH_128;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGeneratePairWiseCredentials(NO_SECURITY_MODE, keySize,
+              provisioningDevID, firstDevID, NULL, &cred1, &cred2));
+    OICFree(firstDevID);
+    OICFree(provisioningDevID);
+}
+
+TEST(PMGeneratePairWiseCredentialsTest, InvalidCred)
+{
+    OicUuid_t *firstDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+    if(firstDevID)
+    {
+        firstDevID->id[0] = 1;
+    }
+    OicUuid_t *SecondDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+    if(SecondDevID)
+    {
+        SecondDevID->id[0] = 2;
+    }
+    OicUuid_t *provisioningDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+    if(provisioningDevID)
+    {
+        provisioningDevID->id[0] = 3;
+    }
+    size_t keySize = OWNER_PSK_LENGTH_128;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGeneratePairWiseCredentials(NO_SECURITY_MODE, keySize,
+              provisioningDevID, firstDevID, SecondDevID, NULL, NULL));
+    OICFree(firstDevID);
+    OICFree(SecondDevID);
+    OICFree(provisioningDevID);
+}
+
+#ifdef __WITH_X509__
+
+TEST(PMGenerateCertificateCredentialsTest, InvalidProvisioningtoolDevID)
+{
+    OicUuid_t *DevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+    if(DevID)
+    {
+        DevID->id[0] = 1;
+    }
+    OicSecCred_t *cred = NULL;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGenerateCertificateCredentials(NULL, DevID, &cred));
+    OICFree(DevID);
+}
+
+TEST(PMGenerateCertificateCredentialsTest, InvalidDevID)
+{
+    OicUuid_t *provisioningDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+    if(provisioningDevID)
+    {
+        provisioningDevID->id[0] = 1;
+    }
+    OicSecCred_t *cred = NULL;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGenerateCertificateCredentials(provisioningDevID,
+              NULL, &cred));
+    OICFree(provisioningDevID);
+}
+
+TEST(PMGenerateCertificateCredentialsTest, InvalidCred)
+{
+    OicUuid_t *provisioningDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+    if(provisioningDevID)
+    {
+        provisioningDevID->id[0] = 1;
+    }
+    OicUuid_t *DevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+    if(DevID)
+    {
+        DevID->id[0] = 1;
+    }
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGenerateCertificateCredentials(provisioningDevID, DevID,
+    NULL));
+    OICFree(provisioningDevID);
+    OICFree(DevID);
+}
+
+#endif // __WITH_X509__
+
index b10129a..ca91b31 100644 (file)
@@ -64,6 +64,18 @@ static void provisioningCB (void* UNUSED1, int UNUSED2, OCProvisionResult_t *UNU
     (void) UNUSED4;
 }
 
+static OCStackResult OTMLoadSecretCallback(OTMContext_t* otmCtx)
+{
+    //dummy callback
+    (void) otmCtx;
+    return OC_STACK_OK;
+}
+
+TEST(OCInitPMTest, NullPath)
+{
+    EXPECT_EQ(OC_STACK_OK, OCInitPM(NULL));
+}
+
 TEST(OCProvisionPairwiseDevicesTest, NullDevice1)
 {
     pDev1.doxm = &defaultDoxm1;
@@ -174,3 +186,42 @@ TEST(OCGetLinkedStatusTest, NULLDeviceID)
     size_t noOfDevices = 0;
     EXPECT_EQ(OC_STACK_INVALID_PARAM, OCGetLinkedStatus(NULL, &list, &noOfDevices));
 }
+
+TEST(OCDeleteUuidListTest, NullUuidList)
+{
+    OCDeleteUuidList(NULL);
+    EXPECT_EQ(1, 1);
+}
+
+TEST(OCDeleteACLListTest, NullACLList)
+{
+    OCDeleteACLList(NULL);
+    EXPECT_EQ(1, 1);
+}
+
+TEST(OCDeletePdAclListTest, NullPdACLList)
+{
+    OCDeletePdAclList(NULL);
+    EXPECT_EQ(1, 1);
+}
+
+TEST(OCDeleteDiscoveredDevicesTest, NullProvisionDevList)
+{
+    OCDeleteDiscoveredDevices(NULL);
+    EXPECT_EQ(1, 1);
+}
+
+TEST(OCSetOwnerTransferCallbackDataTest, NULLCallback)
+{
+    OicSecOxm_t ownershipTransferMethod = OIC_JUST_WORKS;
+    EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCSetOwnerTransferCallbackData(ownershipTransferMethod,
+    NULL));
+}
+
+TEST(OCSetOwnerTransferCallbackDataTest, InvalidOXMType)
+{
+    OicSecOxm_t ownershipTransferMethod = OIC_OXM_COUNT;
+    OTMCallbackData_t stOTMCallbackData = { &OTMLoadSecretCallback, NULL, NULL, NULL};
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSetOwnerTransferCallbackData(ownershipTransferMethod,
+    &stOTMCallbackData));
+}
index f0a0eab..00aa699 100644 (file)
  * limitations under the License.
  *
  * *****************************************************************/
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
 #include "gtest/gtest.h"
-#include "oxmjustworks.h"
-#include "oxmrandompin.h"
-#include "ownershiptransfermanager.h"
 #include "ocstack.h"
 #include "utlist.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "ocprovisioningmanager.h"
+#include "oxmjustworks.h"
+#include "oxmrandompin.h"
+#include "securevirtualresourcetypes.h"
+#include "provisioningdatabasemanager.h"
+#include "srmutility.h"
+#include "doxmresource.h"
+#include "pmtypes.h"
+#include "pmutility.h"
 
 using namespace std;
 
@@ -99,3 +111,428 @@ TEST(RandomPinOxMTest, NullParam)
     res = CreatePinBasedOwnerTransferPayload(&otmCtx2, &payloadRes, &size);
     EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 }
+
+
+/****************************************
+ * Test the OTM modules with sample server
+ ****************************************/
+#define TAG "JUSTWORKS_UNITTEST"
+#define OTM_TIMEOUT 5
+#define DISCOVERY_TIMEOUT 3
+
+#define SVR_DB_PATH "oic_svr_db_client.dat"
+#define UT_PATH "resource/csdk/security/provisioning/unittest"
+char pdb_path[1024];
+char svr_path[1024];
+
+static uint8_t DEFAULT_SVR_DB[] = {
+    0xBF, 0x63, 0x61, 0x63, 0x6C, 0x59, 0x02, 0x57, 0xA2, 0x66, 0x61, 0x63, 0x6C, 0x69, 0x73, 0x74,
+    0xA1, 0x64, 0x61, 0x63, 0x65, 0x73, 0x83, 0xA3, 0x6B, 0x73, 0x75, 0x62, 0x6A, 0x65, 0x63, 0x74,
+    0x75, 0x75, 0x69, 0x64, 0x61, 0x2A, 0x69, 0x72, 0x65, 0x73, 0x6F, 0x75, 0x72, 0x63, 0x65, 0x73,
+    0x83, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x68, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x72, 0x65, 0x73,
+    0x62, 0x72, 0x74, 0x81, 0x6A, 0x6F, 0x69, 0x63, 0x2E, 0x77, 0x6B, 0x2E, 0x72, 0x65, 0x73, 0x62,
+    0x69, 0x66, 0x81, 0x69, 0x6F, 0x69, 0x63, 0x2E, 0x69, 0x66, 0x2E, 0x6C, 0x6C, 0x63, 0x72, 0x65,
+    0x6C, 0x60, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x66, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x64, 0x62,
+    0x72, 0x74, 0x81, 0x68, 0x6F, 0x69, 0x63, 0x2E, 0x77, 0x6B, 0x2E, 0x64, 0x62, 0x69, 0x66, 0x82,
+    0x6F, 0x6F, 0x69, 0x63, 0x2E, 0x69, 0x66, 0x2E, 0x62, 0x61, 0x73, 0x65, 0x6C, 0x69, 0x6E, 0x65,
+    0x68, 0x6F, 0x69, 0x63, 0x2E, 0x69, 0x66, 0x2E, 0x72, 0x63, 0x72, 0x65, 0x6C, 0x60, 0xA4, 0x64,
+    0x68, 0x72, 0x65, 0x66, 0x66, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x70, 0x62, 0x72, 0x74, 0x81, 0x68,
+    0x6F, 0x69, 0x63, 0x2E, 0x77, 0x6B, 0x2E, 0x70, 0x62, 0x69, 0x66, 0x82, 0x6F, 0x6F, 0x69, 0x63,
+    0x2E, 0x69, 0x66, 0x2E, 0x62, 0x61, 0x73, 0x65, 0x6C, 0x69, 0x6E, 0x65, 0x68, 0x6F, 0x69, 0x63,
+    0x2E, 0x69, 0x66, 0x2E, 0x72, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x6A, 0x70, 0x65, 0x72, 0x6D, 0x69,
+    0x73, 0x73, 0x69, 0x6F, 0x6E, 0x02, 0xA3, 0x6B, 0x73, 0x75, 0x62, 0x6A, 0x65, 0x63, 0x74, 0x75,
+    0x75, 0x69, 0x64, 0x61, 0x2A, 0x69, 0x72, 0x65, 0x73, 0x6F, 0x75, 0x72, 0x63, 0x65, 0x73, 0x82,
+    0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x6D, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x73, 0x65, 0x63, 0x2F,
+    0x64, 0x6F, 0x78, 0x6D, 0x62, 0x72, 0x74, 0x81, 0x6A, 0x6F, 0x69, 0x63, 0x2E, 0x72, 0x2E, 0x64,
+    0x6F, 0x78, 0x6D, 0x62, 0x69, 0x66, 0x81, 0x6F, 0x6F, 0x69, 0x63, 0x2E, 0x69, 0x66, 0x2E, 0x62,
+    0x61, 0x73, 0x65, 0x6C, 0x69, 0x6E, 0x65, 0x63, 0x72, 0x65, 0x6C, 0x60, 0xA4, 0x64, 0x68, 0x72,
+    0x65, 0x66, 0x6E, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x73, 0x65, 0x63, 0x2F, 0x70, 0x73, 0x74, 0x61,
+    0x74, 0x62, 0x72, 0x74, 0x81, 0x6B, 0x6F, 0x69, 0x63, 0x2E, 0x72, 0x2E, 0x70, 0x73, 0x74, 0x61,
+    0x74, 0x62, 0x69, 0x66, 0x81, 0x6F, 0x6F, 0x69, 0x63, 0x2E, 0x69, 0x66, 0x2E, 0x62, 0x61, 0x73,
+    0x65, 0x6C, 0x69, 0x6E, 0x65, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x6A, 0x70, 0x65, 0x72, 0x6D, 0x69,
+    0x73, 0x73, 0x69, 0x6F, 0x6E, 0x02, 0xA3, 0x6B, 0x73, 0x75, 0x62, 0x6A, 0x65, 0x63, 0x74, 0x75,
+    0x75, 0x69, 0x64, 0x61, 0x2A, 0x69, 0x72, 0x65, 0x73, 0x6F, 0x75, 0x72, 0x63, 0x65, 0x73, 0x82,
+    0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x6E, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x73, 0x65, 0x63, 0x2F,
+    0x70, 0x63, 0x6F, 0x6E, 0x66, 0x62, 0x72, 0x74, 0x81, 0x6B, 0x6F, 0x69, 0x63, 0x2E, 0x72, 0x2E,
+    0x70, 0x63, 0x6F, 0x6E, 0x66, 0x62, 0x69, 0x66, 0x81, 0x6F, 0x6F, 0x69, 0x63, 0x2E, 0x69, 0x66,
+    0x2E, 0x62, 0x61, 0x73, 0x65, 0x6C, 0x69, 0x6E, 0x65, 0x63, 0x72, 0x65, 0x6C, 0x60, 0xA4, 0x64,
+    0x68, 0x72, 0x65, 0x66, 0x71, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x73, 0x65, 0x63, 0x2F, 0x64, 0x70,
+    0x61, 0x69, 0x72, 0x69, 0x6E, 0x67, 0x62, 0x72, 0x74, 0x81, 0x6E, 0x6F, 0x69, 0x63, 0x2E, 0x72,
+    0x2E, 0x64, 0x70, 0x61, 0x69, 0x72, 0x69, 0x6E, 0x67, 0x62, 0x69, 0x66, 0x81, 0x6F, 0x6F, 0x69,
+    0x63, 0x2E, 0x69, 0x66, 0x2E, 0x62, 0x61, 0x73, 0x65, 0x6C, 0x69, 0x6E, 0x65, 0x63, 0x72, 0x65,
+    0x6C, 0x60, 0x6A, 0x70, 0x65, 0x72, 0x6D, 0x69, 0x73, 0x73, 0x69, 0x6F, 0x6E, 0x02, 0x6A, 0x72,
+    0x6F, 0x77, 0x6E, 0x65, 0x72, 0x75, 0x75, 0x69, 0x64, 0x78, 0x24, 0x36, 0x31, 0x36, 0x34, 0x36,
+    0x64, 0x36, 0x39, 0x2D, 0x36, 0x65, 0x34, 0x34, 0x2D, 0x36, 0x35, 0x37, 0x36, 0x2D, 0x36, 0x39,
+    0x36, 0x33, 0x2D, 0x36, 0x35, 0x35, 0x35, 0x37, 0x35, 0x36, 0x39, 0x36, 0x34, 0x33, 0x30, 0x65,
+    0x70, 0x73, 0x74, 0x61, 0x74, 0x58, 0x79, 0xA7, 0x64, 0x69, 0x73, 0x6F, 0x70, 0xF5, 0x6A, 0x64,
+    0x65, 0x76, 0x69, 0x63, 0x65, 0x75, 0x75, 0x69, 0x64, 0x78, 0x24, 0x36, 0x31, 0x36, 0x34, 0x36,
+    0x64, 0x36, 0x39, 0x2D, 0x36, 0x65, 0x34, 0x34, 0x2D, 0x36, 0x35, 0x37, 0x36, 0x2D, 0x36, 0x39,
+    0x36, 0x33, 0x2D, 0x36, 0x35, 0x35, 0x35, 0x37, 0x35, 0x36, 0x39, 0x36, 0x34, 0x33, 0x30, 0x62,
+    0x63, 0x6D, 0x00, 0x62, 0x74, 0x6D, 0x00, 0x62, 0x6F, 0x6D, 0x03, 0x62, 0x73, 0x6D, 0x03, 0x6A,
+    0x72, 0x6F, 0x77, 0x6E, 0x65, 0x72, 0x75, 0x75, 0x69, 0x64, 0x78, 0x24, 0x36, 0x31, 0x36, 0x34,
+    0x36, 0x64, 0x36, 0x39, 0x2D, 0x36, 0x65, 0x34, 0x34, 0x2D, 0x36, 0x35, 0x37, 0x36, 0x2D, 0x36,
+    0x39, 0x36, 0x33, 0x2D, 0x36, 0x35, 0x35, 0x35, 0x37, 0x35, 0x36, 0x39, 0x36, 0x34, 0x33, 0x30,
+    0x64, 0x64, 0x6F, 0x78, 0x6D, 0x58, 0xC4, 0xA8, 0x64, 0x6F, 0x78, 0x6D, 0x73, 0x81, 0x00, 0x66,
+    0x6F, 0x78, 0x6D, 0x73, 0x65, 0x6C, 0x00, 0x63, 0x73, 0x63, 0x74, 0x01, 0x65, 0x6F, 0x77, 0x6E,
+    0x65, 0x64, 0xF5, 0x6A, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x75, 0x75, 0x69, 0x64, 0x78, 0x24,
+    0x36, 0x31, 0x36, 0x34, 0x36, 0x64, 0x36, 0x39, 0x2D, 0x36, 0x65, 0x34, 0x34, 0x2D, 0x36, 0x35,
+    0x37, 0x36, 0x2D, 0x36, 0x39, 0x36, 0x33, 0x2D, 0x36, 0x35, 0x35, 0x35, 0x37, 0x35, 0x36, 0x39,
+    0x36, 0x34, 0x33, 0x30, 0x6C, 0x64, 0x65, 0x76, 0x6F, 0x77, 0x6E, 0x65, 0x72, 0x75, 0x75, 0x69,
+    0x64, 0x78, 0x24, 0x36, 0x31, 0x36, 0x34, 0x36, 0x64, 0x36, 0x39, 0x2D, 0x36, 0x65, 0x34, 0x34,
+    0x2D, 0x36, 0x35, 0x37, 0x36, 0x2D, 0x36, 0x39, 0x36, 0x33, 0x2D, 0x36, 0x35, 0x35, 0x35, 0x37,
+    0x35, 0x36, 0x39, 0x36, 0x34, 0x33, 0x30, 0x6A, 0x72, 0x6F, 0x77, 0x6E, 0x65, 0x72, 0x75, 0x75,
+    0x69, 0x64, 0x78, 0x24, 0x36, 0x31, 0x36, 0x34, 0x36, 0x64, 0x36, 0x39, 0x2D, 0x36, 0x65, 0x34,
+    0x34, 0x2D, 0x36, 0x35, 0x37, 0x36, 0x2D, 0x36, 0x39, 0x36, 0x33, 0x2D, 0x36, 0x35, 0x35, 0x35,
+    0x37, 0x35, 0x36, 0x39, 0x36, 0x34, 0x33, 0x30, 0x71, 0x78, 0x2E, 0x63, 0x6F, 0x6D, 0x2E, 0x73,
+    0x61, 0x6D, 0x73, 0x75, 0x6E, 0x67, 0x2E, 0x64, 0x70, 0x63, 0xF4, 0xFF
+};
+
+static bool g_doneCB;
+static bool g_callbackResult;
+static pid_t g_myPID1;
+static pid_t g_myPID2;
+
+static const char* g_otmCtx = "Test User Context";
+static OCProvisionDev_t* g_unownedDevices = NULL;
+static OCProvisionDev_t* g_ownedDevices = NULL;
+
+static void GetCurrentWorkingDirectory(char* buf, size_t bufsize)
+{
+    char cwd[1024] = {0};
+    const char* unittest_path = "resource/csdk/security/provisioning/unittest";
+    if(getcwd(cwd, sizeof(cwd)) != NULL)
+    {
+        if(strstr(cwd, unittest_path) == NULL)
+        {
+#if defined __linux__
+#if __x86_64__
+        snprintf(buf, bufsize, "%s/out/linux/x86_64/release/%s/", cwd, unittest_path);
+        snprintf(buf, bufsize, "%s/out/linux/x86_64/release/%s/", cwd, unittest_path);
+#else
+        snprintf(buf, bufsize, "%s/out/linux/x86/release/%s/", cwd, unittest_path);
+        snprintf(buf, bufsize, "%s/out/linux/x86/release/%s/", cwd, unittest_path);
+#endif //__x86_64__
+#endif //defined __linux__
+        }
+        else
+        {
+            snprintf(buf, bufsize, "%s/", cwd);
+        }
+    }
+}
+
+static FILE* fopen_prvnMng(const char* path, const char* mode)
+{
+    (void)path;  // unused |path| parameter
+
+    // input |g_svr_db_fname| internally by force, not using |path| parameter
+    // because |OCPersistentStorage::open| is called |OCPersistentStorage| internally
+    // with its own |SVR_DB_FILE_NAME|
+    char cwd[1024] = {0};
+    char svr_db_path[1024] = {0};
+    GetCurrentWorkingDirectory(cwd, sizeof(cwd));
+    snprintf(svr_db_path, sizeof(svr_db_path), "%s%s", cwd, SVR_DB_PATH);
+    return fopen(svr_db_path, mode);
+}
+
+// callback function(s) for provisioning client using C-level provisioning API
+static void ownershipTransferCB(void* ctx, int UNUSED1, OCProvisionResult_t* UNUSED2, bool hasError)
+{
+    (void)UNUSED1;
+    (void)UNUSED2;
+    (void)ctx;
+
+    if(!hasError)
+    {
+        OIC_LOG_V(INFO, TAG, "Ownership Transfer SUCCEEDED - ctx: %s", (char*) ctx);
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "Ownership Transfer FAILED - ctx: %s", (char*) ctx);
+    }
+    g_callbackResult = !hasError;
+    g_doneCB = true;
+}
+
+
+// callback function(s) for provisioning client using C-level provisioning API
+static void removeDeviceCB(void* ctx, int UNUSED1, OCProvisionResult_t* UNUSED2, bool hasError)
+{
+    (void)UNUSED1;
+    (void)UNUSED2;
+    (void)ctx;
+
+    if(!hasError)
+    {
+        OIC_LOG_V(INFO, TAG, "Remove device request SUCCEEDED - ctx: %s", (char*) ctx);
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "Remove device request FAILED - ctx: %s", (char*) ctx);
+    }
+    g_callbackResult = !hasError;
+    g_doneCB = true;
+}
+
+
+static int waitCallbackRet(void)
+{
+    struct timespec timeout;
+    timeout.tv_sec  = 0;
+    timeout.tv_nsec = 100000000L;
+
+    for(long long i=0; !g_doneCB && OTM_TIMEOUT * 100000000L * 1000L > i; ++i)
+    {
+        nanosleep(&timeout, NULL);
+        if(OC_STACK_OK != OCProcess())
+        {
+            OIC_LOG(ERROR, TAG, "OCStack process error");
+            return -1;
+        }
+    }
+
+    return 0;
+}
+
+TEST(InitForOTM, NullParam)
+{
+    OCStackResult result = OC_STACK_ERROR;
+
+    OTMCallbackData_t otmcb;
+    otmcb.loadSecretCB = LoadSecretJustWorksCallback;
+    otmcb.createSecureSessionCB = CreateSecureSessionJustWorksCallback;
+    otmcb.createSelectOxmPayloadCB = CreateJustWorksSelectOxmPayload;
+    otmcb.createOwnerTransferPayloadCB = CreateJustWorksOwnerTransferPayload;
+
+    static OCPersistentStorage pstStr;
+    pstStr.open = fopen_prvnMng;
+    pstStr.read = fread;
+    pstStr.write = fwrite;
+    pstStr.close = fclose;
+    pstStr.unlink = unlink;
+
+    //Get current path to execute the sample server.
+    char cwd[1024] = {0};
+    char server1_path[1024] = {0};
+    char server2_path[1024] = {0};
+    char pdb_path[1024] = {0};
+    char del_cmd[1024] = {0};
+    char svrdb_path[1024] = {0};
+    FILE* fp = NULL;
+
+    GetCurrentWorkingDirectory(cwd, sizeof(cwd));
+    EXPECT_TRUE(0 < strlen(cwd));
+
+    //Delete previous PDB, if exist.
+    GetCurrentWorkingDirectory(cwd, sizeof(cwd));
+    snprintf(del_cmd, sizeof(del_cmd), "rm -rf %stest.db", cwd);
+    system(del_cmd);
+
+    //Delete previous SVR DB, if exist.
+    snprintf(del_cmd, sizeof(del_cmd), "rm -rf %s%s", cwd, SVR_DB_PATH);
+    system(del_cmd);
+
+    //Generate default SVR DB.
+    snprintf(svrdb_path, sizeof(svrdb_path), "%s%s", cwd, SVR_DB_PATH);
+    fp = fopen(svrdb_path, "w");
+    if(NULL != fp)
+    {
+        size_t numberItems = fwrite(DEFAULT_SVR_DB, 1, sizeof(DEFAULT_SVR_DB), fp);
+        fclose(fp);
+        ASSERT_TRUE(sizeof(DEFAULT_SVR_DB) == numberItems);
+    }
+
+    //Execute sample server to perform ownership transfer
+    int status1 = 0;
+    int status2 = 0;
+    if(0 == (g_myPID1 = fork()))
+    {
+        snprintf(server1_path, sizeof(server1_path), "%ssample_server1", cwd);
+        status1 = system(server1_path);
+        (void)status1;
+    }
+    if(0 == (g_myPID2 = fork()))
+    {
+        snprintf(server2_path, sizeof(server2_path), "%ssample_server2", cwd);
+        status2= system(server2_path);
+        (void)status2;
+    }
+
+    // register the persistent storage handler for SVR
+    result = OCRegisterPersistentStorageHandler(&pstStr);
+    EXPECT_EQ(OC_STACK_OK, result);
+
+    // initialize OC stack and provisioning manager
+    result = OCInit(NULL, 0, OC_CLIENT_SERVER);
+    EXPECT_EQ(OC_STACK_OK, result);
+
+    //initialize Provisioning DB Manager
+
+    snprintf(pdb_path, sizeof(pdb_path), "%stest.db", cwd);
+    result = OCInitPM(pdb_path);
+    EXPECT_EQ(OC_STACK_OK, result);
+
+    // register callback function(s) for Justworks OxM
+    result = OCSetOwnerTransferCallbackData(OIC_JUST_WORKS, &otmcb);
+    EXPECT_EQ(OC_STACK_OK, result);
+
+    g_doneCB = false;
+    g_callbackResult = false;
+}
+
+
+TEST(PerformUnownedDeviceDiscovery, NullParam)
+{
+    OCStackResult result = OC_STACK_ERROR;
+
+    OIC_LOG(INFO, TAG, "Discovering Only Unowned Devices on Network..\n");
+    result = OCDiscoverUnownedDevices(DISCOVERY_TIMEOUT, &g_unownedDevices);
+    EXPECT_EQ(OC_STACK_OK, result);
+
+    int NumOfUnownDevice = 0;
+    OCProvisionDev_t* tempDev = g_unownedDevices;
+    while(tempDev)
+    {
+        NumOfUnownDevice++;
+        tempDev = tempDev->next;
+    }
+    EXPECT_EQ(2, NumOfUnownDevice);
+}
+
+TEST(PerformJustWorksOxM, NullParam)
+{
+    OCStackResult result = OC_STACK_ERROR;
+
+    OIC_LOG(INFO, TAG, "Try Ownership Transfer for Unowned Devices...\n");
+    result = OCDoOwnershipTransfer((void*)g_otmCtx, g_unownedDevices, ownershipTransferCB);
+    EXPECT_EQ(OC_STACK_OK, result);
+
+    if(waitCallbackRet())  // input |g_doneCB| flag implicitly
+    {
+        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
+        return;
+    }
+    OIC_LOG(INFO, TAG, "Registered Discovered Unowned Device...\n");
+
+    EXPECT_EQ(true, g_callbackResult);
+    EXPECT_EQ(true, g_doneCB);
+}
+
+
+TEST(PerformOwnedDeviceDiscovery, NullParam)
+{
+    OCStackResult result = OC_STACK_ERROR;
+
+    OIC_LOG(INFO, TAG, "Discovering Only Owned Devices on Network..\n");
+    result = OCDiscoverOwnedDevices(DISCOVERY_TIMEOUT, &g_ownedDevices);
+    EXPECT_EQ(OC_STACK_OK, result);
+
+    int NumOfOwnDevice = 0;
+    OCProvisionDev_t* tempDev = g_ownedDevices;
+    while(tempDev)
+    {
+        NumOfOwnDevice++;
+        tempDev = tempDev->next;
+    }
+
+    EXPECT_EQ(2/*Server*/ , NumOfOwnDevice);
+}
+
+TEST(PerformLinkDevices, NullParam)
+{
+    OicUuid_t myUuid;
+    OCStackResult result = OC_STACK_ERROR;
+    result = GetDoxmDeviceID(&myUuid);
+    EXPECT_EQ(OC_STACK_OK, result);
+
+    //Extract target device except PT to perform link devices.
+    OCProvisionDev_t* dev1 = NULL;
+    OCProvisionDev_t* dev2 = NULL;
+    OCProvisionDev_t* tempDev = g_ownedDevices;
+
+    while(tempDev)
+    {
+        if(memcmp(tempDev->doxm->deviceID.id, myUuid.id, UUID_LENGTH) != 0)
+        {
+            if(NULL == dev1)
+            {
+                dev1 = tempDev;
+            }
+            else if(NULL == dev2)
+            {
+                dev2 = tempDev;
+                break;
+            }
+            else
+            {
+                break;
+            }
+        }
+        tempDev = tempDev->next;
+    }
+    EXPECT_TRUE(NULL != dev1);
+    EXPECT_TRUE(NULL != dev2);
+
+    // TODO: Pairwise provisioning (Cred & ACL)
+    // TODO: This part will be updated after ACL and credential data-structure is updated.
+
+    EXPECT_EQ(OC_STACK_OK, result);
+}
+
+TEST(PerformUnlinkDevices, NullParam)
+{
+    OCStackResult result = OC_STACK_OK;
+
+    // TODO: Unlink devices
+    // TODO: This part will be updated after ACL and credential data-structure is updated.
+
+    EXPECT_EQ(OC_STACK_OK, result);
+}
+
+TEST(PerformRemoveDevice, NullParam)
+{
+    OicUuid_t myUuid;
+    OCStackResult result = OC_STACK_ERROR;
+    result = GetDoxmDeviceID(&myUuid);
+    EXPECT_EQ(OC_STACK_OK, result);
+
+    //Extract target device except PT to perform remove device.
+    OCProvisionDev_t* removeDev = g_ownedDevices;
+    while(removeDev)
+    {
+        if(memcmp(removeDev->doxm->deviceID.id, myUuid.id, UUID_LENGTH) != 0)
+        {
+            break;
+        }
+        removeDev = removeDev->next;
+    }
+    EXPECT_TRUE(NULL != removeDev);
+
+    g_doneCB = false;
+    g_callbackResult = false;
+
+    result = OCRemoveDevice((void*)g_otmCtx, DISCOVERY_TIMEOUT, removeDev, removeDeviceCB);
+    EXPECT_EQ(OC_STACK_OK, result);
+    EXPECT_EQ(true, g_callbackResult);
+    EXPECT_EQ(true, g_doneCB);
+}
+
+TEST(FinalizeOTMTest, NullParam)
+{
+    OCStackResult result = OCStop();
+    EXPECT_EQ(OC_STACK_OK, result);
+
+    PMDeleteDeviceList(g_unownedDevices);
+    PMDeleteDeviceList(g_ownedDevices);
+    result = PDMClose();
+    EXPECT_EQ(OC_STACK_OK, result);
+
+    kill(g_myPID2, SIGKILL);
+    kill(g_myPID1, SIGKILL);
+
+    int interpreter_res1 = system("pkill -f \"sample_server1\"");
+    EXPECT_TRUE(0 <= interpreter_res1);
+    int interpreter_res2 = system("pkill -f \"sample_server2\"");
+    EXPECT_TRUE(0 <= interpreter_res2);
+}
+
diff --git a/resource/csdk/security/provisioning/unittest/sampleserver1.cpp b/resource/csdk/security/provisioning/unittest/sampleserver1.cpp
new file mode 100644 (file)
index 0000000..056e8c1
--- /dev/null
@@ -0,0 +1,583 @@
+/******************************************************************
+*
+* 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.
+*
+******************************************************************/
+///////////////////////////////////////////////////////////////////////
+//NOTE :  This sample server is generated based on ocserverbasicops.cpp
+///////////////////////////////////////////////////////////////////////
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <signal.h>
+#include <pthread.h>
+#include "ocstack.h"
+#include "logger.h"
+#include "ocpayload.h"
+#include "oic_string.h"
+
+#define TAG "UNITTEST_SERVER_1"
+
+int gQuitFlag = 0;
+
+/* Structure to represent a LED resource */
+typedef struct LEDRESOURCE{
+    OCResourceHandle handle;
+    bool state;
+    int power;
+} LEDResource;
+
+static LEDResource LED;
+// This variable determines instance number of the LED resource.
+// Used by POST method to create a new instance of LED resource.
+static int gCurrLedInstance = 0;
+#define SAMPLE_MAX_NUM_POST_INSTANCE  2
+static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
+
+char *gResourceUri= (char *)"/a/led";
+
+//Secure Virtual Resource database for Iotivity Server
+//It contains Server's Identity and the PSK credentials
+//of other devices which the server trusts
+static char CRED_FILE[] = "oic_svr_db_server1.dat";
+
+static uint8_t DEFAULT_SVR_DB[] = {
+    0xBF, 0x63, 0x61, 0x63, 0x6C, 0x59, 0x02, 0x76, 0xA2, 0x66, 0x61, 0x63, 0x6C, 0x69, 0x73, 0x74,
+    0xA1, 0x64, 0x61, 0x63, 0x65, 0x73, 0x84, 0xA3, 0x6B, 0x73, 0x75, 0x62, 0x6A, 0x65, 0x63, 0x74,
+    0x75, 0x75, 0x69, 0x64, 0x61, 0x2A, 0x69, 0x72, 0x65, 0x73, 0x6F, 0x75, 0x72, 0x63, 0x65, 0x73,
+    0x86, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x68, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x72, 0x65, 0x73,
+    0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0xA4, 0x64, 0x68,
+    0x72, 0x65, 0x66, 0x66, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x64, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62,
+    0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x66, 0x2F, 0x6F,
+    0x69, 0x63, 0x2F, 0x70, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66,
+    0x60, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x6A, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x72, 0x65, 0x73,
+    0x2F, 0x64, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0xA4,
+    0x64, 0x68, 0x72, 0x65, 0x66, 0x70, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x72, 0x65, 0x73, 0x2F, 0x74,
+    0x79, 0x70, 0x65, 0x73, 0x2F, 0x64, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62,
+    0x69, 0x66, 0x60, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x6D, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x70,
+    0x72, 0x65, 0x73, 0x65, 0x6E, 0x63, 0x65, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60,
+    0x62, 0x69, 0x66, 0x60, 0x6A, 0x70, 0x65, 0x72, 0x6D, 0x69, 0x73, 0x73, 0x69, 0x6F, 0x6E, 0x02,
+    0xA3, 0x6B, 0x73, 0x75, 0x62, 0x6A, 0x65, 0x63, 0x74, 0x75, 0x75, 0x69,  0x64, 0x61, 0x2A, 0x69,
+    0x72, 0x65, 0x73, 0x6F, 0x75, 0x72, 0x63, 0x65, 0x73, 0x84, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66,
+    0x6D, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x73, 0x65, 0x63, 0x2F, 0x64, 0x6F, 0x78, 0x6D, 0x63, 0x72,
+    0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0xA4, 0x64, 0x68, 0x72, 0x65,
+    0x66, 0x6E, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x73, 0x65, 0x63, 0x2F, 0x70, 0x73, 0x74, 0x61, 0x74,
+    0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0xA4, 0x64, 0x68,
+    0x72, 0x65, 0x66, 0x6C, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x73, 0x65, 0x63, 0x2F, 0x61, 0x63, 0x6C,
+    0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0xA4, 0x64, 0x68,
+    0x72, 0x65, 0x66, 0x6D, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x73, 0x65, 0x63, 0x2F, 0x63, 0x72, 0x65,
+    0x64, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0x6A, 0x70,
+    0x65, 0x72, 0x6D, 0x69, 0x73, 0x73, 0x69, 0x6F, 0x6E, 0x06, 0xA3, 0x6B, 0x73, 0x75, 0x62, 0x6A,
+    0x65, 0x63, 0x74, 0x75, 0x75, 0x69, 0x64, 0x61, 0x2A, 0x69, 0x72, 0x65, 0x73, 0x6F, 0x75, 0x72,
+    0x63, 0x65, 0x73, 0x82, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x6E, 0x2F, 0x6F, 0x69, 0x63, 0x2F,
+    0x73, 0x65, 0x63, 0x2F, 0x70, 0x63, 0x6F, 0x6E, 0x66, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72,
+    0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x71, 0x2F, 0x6F, 0x69,
+    0x63, 0x2F, 0x73, 0x65, 0x63, 0x2F, 0x64, 0x70, 0x61, 0x69, 0x72, 0x69, 0x6E, 0x67, 0x63, 0x72,
+    0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0x6A, 0x70, 0x65, 0x72, 0x6D,
+    0x69, 0x73, 0x73, 0x69, 0x6F, 0x6E, 0x06, 0xA3, 0x6B, 0x73, 0x75, 0x62, 0x6A, 0x65, 0x63, 0x74,
+    0x75, 0x75, 0x69, 0x64, 0x61, 0x2A, 0x69, 0x72, 0x65, 0x73, 0x6F, 0x75, 0x72, 0x63, 0x65, 0x73,
+    0x81, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x6C, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x73, 0x65, 0x63,
+    0x2F, 0x76, 0x65, 0x72, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66,
+    0x60, 0x6A, 0x70, 0x65, 0x72, 0x6D, 0x69, 0x73, 0x73, 0x69, 0x6F, 0x6E, 0x02, 0x6A, 0x72, 0x6F,
+    0x77, 0x6E, 0x65, 0x72, 0x75, 0x75, 0x69, 0x64, 0x78, 0x24, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
+    0x31, 0x31, 0x2D, 0x31, 0x31, 0x31, 0x31, 0x2D, 0x31, 0x31, 0x31, 0x31, 0x2D, 0x31, 0x31, 0x31,
+    0x31, 0x2D, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x65, 0x70,
+    0x73, 0x74, 0x61, 0x74, 0x58, 0x79, 0xA7, 0x64, 0x69, 0x73, 0x6F, 0x70, 0xF4, 0x6A, 0x64, 0x65,
+    0x76, 0x69, 0x63, 0x65, 0x75, 0x75, 0x69, 0x64, 0x78, 0x24, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
+    0x31, 0x31, 0x2D, 0x31, 0x31, 0x31, 0x31, 0x2D, 0x31, 0x31, 0x31, 0x31, 0x2D, 0x31, 0x31, 0x31,
+    0x31, 0x2D, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x62, 0x63,
+    0x6D, 0x02, 0x62, 0x74, 0x6D, 0x00, 0x62, 0x6F, 0x6D, 0x03, 0x62, 0x73, 0x6D, 0x03, 0x6A, 0x72,
+    0x6F, 0x77, 0x6E, 0x65, 0x72, 0x75, 0x75, 0x69, 0x64, 0x78, 0x24, 0x31, 0x31, 0x31, 0x31, 0x31,
+    0x31, 0x31, 0x31, 0x2D, 0x31, 0x31, 0x31, 0x31, 0x2D, 0x31, 0x31, 0x31, 0x31, 0x2D, 0x31, 0x31,
+    0x31, 0x31, 0x2D, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x64,
+    0x64, 0x6F, 0x78, 0x6D, 0x58, 0xB6, 0xA8, 0x64, 0x6F, 0x78, 0x6D, 0x73, 0x81, 0x00, 0x66, 0x6F,
+    0x78, 0x6D, 0x73, 0x65, 0x6C, 0x00, 0x63, 0x73, 0x63, 0x74, 0x01, 0x65, 0x6F, 0x77, 0x6E, 0x65,
+    0x64, 0xF4, 0x6A, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x75, 0x75, 0x69, 0x64, 0x78, 0x24, 0x31,
+    0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x2D, 0x31, 0x31, 0x31, 0x31, 0x2D, 0x31, 0x31, 0x31,
+    0x31, 0x2D, 0x31, 0x31, 0x31, 0x31, 0x2D, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
+    0x31, 0x31, 0x31, 0x6C, 0x64, 0x65, 0x76, 0x6F, 0x77, 0x6E, 0x65, 0x72, 0x75, 0x75, 0x69, 0x64,
+    0x78, 0x24, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x2D, 0x30, 0x30, 0x30, 0x30, 0x2D,
+    0x30, 0x30, 0x30, 0x30, 0x2D, 0x30, 0x30, 0x30, 0x30, 0x2D, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
+    0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x6A, 0x72, 0x6F, 0x77, 0x6E, 0x65, 0x72, 0x75, 0x75, 0x69,
+    0x64, 0x78, 0x24, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x2D, 0x31, 0x31, 0x31, 0x31,
+    0x2D, 0x31, 0x31, 0x31, 0x31, 0x2D, 0x31, 0x31, 0x31, 0x31, 0x2D, 0x31, 0x31, 0x31, 0x31, 0x31,
+    0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x63, 0x64, 0x70, 0x63, 0xF5, 0xFF
+};
+
+/* Function that creates a new LED resource by calling the
+ * OCCreateResource() method.
+ */
+int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
+
+/* This method converts the payload to JSON format */
+OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
+
+/* Following methods process the PUT, GET, POST
+ * requests
+ */
+OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
+                                         OCRepPayload **payload);
+OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
+                                         OCRepPayload **payload);
+OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
+                                        OCEntityHandlerResponse *response,
+                                        OCRepPayload **payload);
+
+/* Entity Handler callback functions */
+OCEntityHandlerResult
+OCEntityHandlerCb (OCEntityHandlerFlag flag,
+        OCEntityHandlerRequest *entityHandlerRequest,
+        void* callbackParam);
+
+const char *getResult(OCStackResult result) {
+    switch (result) {
+    case OC_STACK_OK:
+        return "OC_STACK_OK";
+    case OC_STACK_RESOURCE_CREATED:
+        return "OC_STACK_RESOURCE_CREATED";
+    case OC_STACK_RESOURCE_DELETED:
+        return "OC_STACK_RESOURCE_DELETED";
+    case OC_STACK_INVALID_URI:
+        return "OC_STACK_INVALID_URI";
+    case OC_STACK_INVALID_QUERY:
+        return "OC_STACK_INVALID_QUERY";
+    case OC_STACK_INVALID_IP:
+        return "OC_STACK_INVALID_IP";
+    case OC_STACK_INVALID_PORT:
+        return "OC_STACK_INVALID_PORT";
+    case OC_STACK_INVALID_CALLBACK:
+        return "OC_STACK_INVALID_CALLBACK";
+    case OC_STACK_INVALID_METHOD:
+        return "OC_STACK_INVALID_METHOD";
+    case OC_STACK_NO_MEMORY:
+        return "OC_STACK_NO_MEMORY";
+    case OC_STACK_COMM_ERROR:
+        return "OC_STACK_COMM_ERROR";
+    case OC_STACK_INVALID_PARAM:
+        return "OC_STACK_INVALID_PARAM";
+    case OC_STACK_NOTIMPL:
+        return "OC_STACK_NOTIMPL";
+    case OC_STACK_NO_RESOURCE:
+        return "OC_STACK_NO_RESOURCE";
+    case OC_STACK_RESOURCE_ERROR:
+        return "OC_STACK_RESOURCE_ERROR";
+    case OC_STACK_SLOW_RESOURCE:
+        return "OC_STACK_SLOW_RESOURCE";
+    case OC_STACK_NO_OBSERVERS:
+        return "OC_STACK_NO_OBSERVERS";
+    #ifdef WITH_PRESENCE
+    case OC_STACK_PRESENCE_STOPPED:
+        return "OC_STACK_PRESENCE_STOPPED";
+    #endif
+    case OC_STACK_ERROR:
+        return "OC_STACK_ERROR";
+    default:
+        return "UNKNOWN";
+    }
+}
+
+OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
+{
+    OCRepPayload* payload = OCRepPayloadCreate();
+    if(!payload)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
+        return NULL;
+    }
+
+    OCRepPayloadSetUri(payload, uri);
+    OCRepPayloadSetPropBool(payload, "state", state);
+    OCRepPayloadSetPropInt(payload, "power", power);
+
+    return payload;
+}
+
+//This function takes the request as an input and returns the response
+OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
+{
+    if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+    {
+        OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
+        return NULL;
+    }
+
+    OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
+
+    LEDResource *currLEDResource = &LED;
+
+    if (ehRequest->resource == gLedInstance[0].handle)
+    {
+        currLEDResource = &gLedInstance[0];
+        gResourceUri = (char *) "/a/led/0";
+    }
+    else if (ehRequest->resource == gLedInstance[1].handle)
+    {
+        currLEDResource = &gLedInstance[1];
+        gResourceUri = (char *) "/a/led/1";
+    }
+
+    if(OC_REST_PUT == ehRequest->method)
+    {
+        // Get pointer to query
+        int64_t pow;
+        if(OCRepPayloadGetPropInt(input, "power", &pow))
+        {
+            currLEDResource->power =pow;
+        }
+
+        bool state;
+        if(OCRepPayloadGetPropBool(input, "state", &state))
+        {
+            currLEDResource->state = state;
+        }
+    }
+
+    return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
+}
+
+OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
+        OCRepPayload **payload)
+{
+    OCEntityHandlerResult ehResult;
+
+    OCRepPayload *getResp = constructResponse(ehRequest);
+
+    if(getResp)
+    {
+        *payload = getResp;
+        ehResult = OC_EH_OK;
+    }
+    else
+    {
+        ehResult = OC_EH_ERROR;
+    }
+
+    return ehResult;
+}
+
+OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
+        OCRepPayload **payload)
+{
+    OCEntityHandlerResult ehResult;
+
+    OCRepPayload *putResp = constructResponse(ehRequest);
+
+    if(putResp)
+    {
+        *payload = putResp;
+        ehResult = OC_EH_OK;
+    }
+    else
+    {
+        ehResult = OC_EH_ERROR;
+    }
+
+    return ehResult;
+}
+
+OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
+        OCEntityHandlerResponse *response, OCRepPayload **payload)
+{
+    OCRepPayload *respPLPost_led = NULL;
+    OCEntityHandlerResult ehResult = OC_EH_OK;
+
+    /*
+     * The entity handler determines how to process a POST request.
+     * Per the REST paradigm, POST can also be used to update representation of existing
+     * resource or create a new resource.
+     * In the sample below, if the POST is for /a/led then a new instance of the LED
+     * resource is created with default representation (if representation is included in
+     * POST payload it can be used as initial values) as long as the instance is
+     * lesser than max new instance count. Once max instance count is reached, POST on
+     * /a/led updated the representation of /a/led (just like PUT)
+     */
+
+    if (ehRequest->resource == LED.handle)
+    {
+        if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
+        {
+            // Create new LED instance
+            char newLedUri[15] = "/a/led/";
+            int newLedUriLength = strlen(newLedUri);
+            snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
+
+            respPLPost_led = OCRepPayloadCreate();
+            OCRepPayloadSetUri(respPLPost_led, gResourceUri);
+            OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
+
+            if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
+            {
+                OIC_LOG (INFO, TAG, "Created new LED instance");
+                gLedInstance[gCurrLedInstance].state = 0;
+                gLedInstance[gCurrLedInstance].power = 0;
+                gCurrLedInstance++;
+                strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
+                ehResult = OC_EH_RESOURCE_CREATED;
+            }
+        }
+        else
+        {
+            respPLPost_led = constructResponse(ehRequest);
+        }
+    }
+    else
+    {
+        for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
+        {
+            if (ehRequest->resource == gLedInstance[i].handle)
+            {
+                if (i == 0)
+                {
+                    respPLPost_led = constructResponse(ehRequest);
+                    break;
+                }
+                else if (i == 1)
+                {
+                    respPLPost_led = constructResponse(ehRequest);
+                }
+            }
+        }
+    }
+
+    if (respPLPost_led != NULL)
+    {
+        *payload = respPLPost_led;
+        ehResult = OC_EH_OK;
+    }
+    else
+    {
+        OIC_LOG_V (INFO, TAG, "Payload was NULL");
+        ehResult = OC_EH_ERROR;
+    }
+
+    return ehResult;
+}
+
+OCEntityHandlerResult
+OCEntityHandlerCb (OCEntityHandlerFlag flag,
+        OCEntityHandlerRequest *entityHandlerRequest,
+        void* callbackParam)
+{
+    OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
+    (void)callbackParam;
+    OCEntityHandlerResult ehResult = OC_EH_ERROR;
+
+    OCEntityHandlerResponse response;
+    memset(&response, 0, sizeof(response));
+
+    // Validate pointer
+    if (!entityHandlerRequest)
+    {
+        OIC_LOG (ERROR, TAG, "Invalid request pointer");
+        return OC_EH_ERROR;
+    }
+
+    OCRepPayload* payload = NULL;
+
+    if (flag & OC_REQUEST_FLAG)
+    {
+        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        if (entityHandlerRequest)
+        {
+            if (OC_REST_GET == entityHandlerRequest->method)
+            {
+                OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
+                ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
+            }
+            else if (OC_REST_PUT == entityHandlerRequest->method)
+            {
+                OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
+                ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
+            }
+            else if (OC_REST_POST == entityHandlerRequest->method)
+            {
+                OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
+                ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
+            }
+            else
+            {
+                OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+                        entityHandlerRequest->method);
+                ehResult = OC_EH_ERROR;
+            }
+
+            if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
+            {
+                // Format the response.  Note this requires some info about the request
+                response.requestHandle = entityHandlerRequest->requestHandle;
+                response.resourceHandle = entityHandlerRequest->resource;
+                response.ehResult = ehResult;
+                response.payload = (OCPayload*)(payload);
+                response.numSendVendorSpecificHeaderOptions = 0;
+                memset(response.sendVendorSpecificHeaderOptions, 0,
+                       sizeof(response.sendVendorSpecificHeaderOptions));
+                memset(response.resourceUri, 0, sizeof(response.resourceUri));
+                // Indicate that response is NOT in a persistent buffer
+                response.persistentBufferFlag = 0;
+
+                // Send the response
+                if (OCDoResponse(&response) != OC_STACK_OK)
+                {
+                    OIC_LOG(ERROR, TAG, "Error sending response");
+                    ehResult = OC_EH_ERROR;
+                }
+            }
+        }
+    }
+
+    OCPayloadDestroy(response.payload);
+    return ehResult;
+}
+
+/* SIGINT handler: set gQuitFlag to 1 for graceful termination */
+void handleSigInt(int signum)
+{
+    if (signum == SIGINT)
+    {
+        gQuitFlag = 1;
+    }
+}
+
+static void GetCurrentWorkingDirectory(char* buf, size_t bufsize)
+{
+    char cwd[1024] = {0};
+    const char* unittest_path = "resource/csdk/security/provisioning/unittest";
+    if(getcwd(cwd, sizeof(cwd)) != NULL)
+    {
+        if(strstr(cwd, unittest_path) == NULL)
+        {
+#if defined __linux__
+#if __x86_64__
+        snprintf(buf, bufsize, "%s/out/linux/x86_64/release/%s/", cwd, unittest_path);
+        snprintf(buf, bufsize, "%s/out/linux/x86_64/release/%s/", cwd, unittest_path);
+#else
+        snprintf(buf, bufsize, "%s/out/linux/x86/release/%s/", cwd, unittest_path);
+        snprintf(buf, bufsize, "%s/out/linux/x86/release/%s/", cwd, unittest_path);
+#endif //__x86_64__
+#endif //defined __linux__
+        }
+        else
+        {
+            snprintf(buf, bufsize, "%s/", cwd);
+        }
+    }
+}
+
+FILE* server_fopen(const char *path, const char *mode)
+{
+    (void)path;
+    char cwd[1024] = {0};
+    char cred_path[1024] = {0};
+    GetCurrentWorkingDirectory(cwd, sizeof(cwd));
+    snprintf(cred_path, sizeof(cred_path), "%s%s", cwd, CRED_FILE);
+    return fopen(cred_path, mode);
+}
+
+int main()
+{
+    struct timespec timeout;
+
+    //Delete previous SVR DB, if exist.
+    char cwd[1024] = {0};
+    char cred_path[1024] = {0};
+    char del_cmd[1024] = {0};
+    FILE* fp = NULL;
+    GetCurrentWorkingDirectory(cwd, sizeof(cwd));
+    snprintf(del_cmd, sizeof(del_cmd), "rm -rf %s%s", cwd, CRED_FILE);
+    system(del_cmd);
+
+    //Generate default SVR DB.
+    snprintf(cred_path, sizeof(cred_path), "%s%s", cwd, CRED_FILE);
+    fp = fopen(cred_path, "w");
+    if(NULL != fp)
+    {
+        size_t numberItems = fwrite(DEFAULT_SVR_DB, 1, sizeof(DEFAULT_SVR_DB), fp);
+        if(sizeof(DEFAULT_SVR_DB) != numberItems)
+        {
+            OIC_LOG_V(ERROR, TAG, "Failed to initialize SVR DB (%s)", cred_path);
+            fclose(fp);
+            return -1;
+        }
+        fclose(fp);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OCServer is starting...");
+
+    // Initialize Persistent Storage for SVR database
+    OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
+
+    OCRegisterPersistentStorageHandler(&ps);
+
+    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "OCStack init error");
+        return 0;
+    }
+
+    /*
+     * Declare and create the example resource: LED
+     */
+    createLEDResource(gResourceUri, &LED, false, 0);
+
+    timeout.tv_sec  = 0;
+    timeout.tv_nsec = 100000000L;
+
+    // Break from loop with Ctrl-C
+    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    signal(SIGINT, handleSigInt);
+    while (!gQuitFlag)
+    {
+        if (OCProcess() != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG, "OCStack process error");
+            return 0;
+        }
+        nanosleep(&timeout, NULL);
+    }
+
+    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+
+    if (OCStop() != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "OCStack process error");
+    }
+
+    return 0;
+}
+
+int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
+{
+    if (!uri)
+    {
+        OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
+        return -1;
+    }
+
+    ledResource->state = resourceState;
+    ledResource->power= resourcePower;
+    OCStackResult res = OCCreateResource(&(ledResource->handle),
+            "core.led",
+            OC_RSRVD_INTERFACE_DEFAULT,
+            uri,
+            OCEntityHandlerCb,
+            NULL,
+            OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
+    OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
+
+    return 0;
+}
diff --git a/resource/csdk/security/provisioning/unittest/sampleserver2.cpp b/resource/csdk/security/provisioning/unittest/sampleserver2.cpp
new file mode 100644 (file)
index 0000000..c500ec7
--- /dev/null
@@ -0,0 +1,583 @@
+/******************************************************************
+*
+* 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.
+*
+******************************************************************/
+///////////////////////////////////////////////////////////////////////
+//NOTE :  This sample server is generated based on ocserverbasicops.cpp
+///////////////////////////////////////////////////////////////////////
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <signal.h>
+#include <pthread.h>
+#include "ocstack.h"
+#include "logger.h"
+#include "ocpayload.h"
+#include "oic_string.h"
+
+#define TAG "UNITTEST_SERVER_2"
+
+int gQuitFlag = 0;
+
+/* Structure to represent a LED resource */
+typedef struct LEDRESOURCE{
+    OCResourceHandle handle;
+    bool state;
+    int power;
+} LEDResource;
+
+static LEDResource LED;
+// This variable determines instance number of the LED resource.
+// Used by POST method to create a new instance of LED resource.
+static int gCurrLedInstance = 0;
+#define SAMPLE_MAX_NUM_POST_INSTANCE  2
+static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
+
+char *gResourceUri= (char *)"/a/led";
+
+//Secure Virtual Resource database for Iotivity Server
+//It contains Server's Identity and the PSK credentials
+//of other devices which the server trusts
+static char CRED_FILE[] = "oic_svr_db_server2.dat";
+
+static uint8_t DEFAULT_SVR_DB[] = {
+    0xBF, 0x63, 0x61, 0x63, 0x6C, 0x59, 0x02, 0x76, 0xA2, 0x66, 0x61, 0x63, 0x6C, 0x69, 0x73, 0x74,
+    0xA1, 0x64, 0x61, 0x63, 0x65, 0x73, 0x84, 0xA3, 0x6B, 0x73, 0x75, 0x62, 0x6A, 0x65, 0x63, 0x74,
+    0x75, 0x75, 0x69, 0x64, 0x61, 0x2A, 0x69, 0x72, 0x65, 0x73, 0x6F, 0x75, 0x72, 0x63, 0x65, 0x73,
+    0x86, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x68, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x72, 0x65, 0x73,
+    0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0xA4, 0x64, 0x68,
+    0x72, 0x65, 0x66, 0x66, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x64, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62,
+    0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x66, 0x2F, 0x6F,
+    0x69, 0x63, 0x2F, 0x70, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66,
+    0x60, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x6A, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x72, 0x65, 0x73,
+    0x2F, 0x64, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0xA4,
+    0x64, 0x68, 0x72, 0x65, 0x66, 0x70, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x72, 0x65, 0x73, 0x2F, 0x74,
+    0x79, 0x70, 0x65, 0x73, 0x2F, 0x64, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62,
+    0x69, 0x66, 0x60, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x6D, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x70,
+    0x72, 0x65, 0x73, 0x65, 0x6E, 0x63, 0x65, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60,
+    0x62, 0x69, 0x66, 0x60, 0x6A, 0x70, 0x65, 0x72, 0x6D, 0x69, 0x73, 0x73, 0x69, 0x6F, 0x6E, 0x02,
+    0xA3, 0x6B, 0x73, 0x75, 0x62, 0x6A, 0x65, 0x63, 0x74, 0x75, 0x75, 0x69, 0x64, 0x61, 0x2A, 0x69,
+    0x72, 0x65, 0x73, 0x6F, 0x75, 0x72, 0x63, 0x65, 0x73, 0x84, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66,
+    0x6D, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x73, 0x65, 0x63, 0x2F, 0x64, 0x6F, 0x78, 0x6D, 0x63, 0x72,
+    0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0xA4, 0x64, 0x68, 0x72, 0x65,
+    0x66, 0x6E, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x73, 0x65, 0x63, 0x2F, 0x70, 0x73, 0x74, 0x61, 0x74,
+    0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0xA4, 0x64, 0x68,
+    0x72, 0x65, 0x66, 0x6C, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x73, 0x65, 0x63, 0x2F, 0x61, 0x63, 0x6C,
+    0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0xA4, 0x64, 0x68,
+    0x72, 0x65, 0x66, 0x6D, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x73, 0x65, 0x63, 0x2F, 0x63, 0x72, 0x65,
+    0x64, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0x6A, 0x70,
+    0x65, 0x72, 0x6D, 0x69, 0x73, 0x73, 0x69, 0x6F, 0x6E, 0x06, 0xA3, 0x6B, 0x73, 0x75, 0x62, 0x6A,
+    0x65, 0x63, 0x74, 0x75, 0x75, 0x69, 0x64, 0x61, 0x2A, 0x69, 0x72, 0x65, 0x73, 0x6F, 0x75, 0x72,
+    0x63, 0x65, 0x73, 0x82, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x6E, 0x2F, 0x6F, 0x69, 0x63, 0x2F,
+    0x73, 0x65, 0x63, 0x2F, 0x70, 0x63, 0x6F, 0x6E, 0x66, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72,
+    0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x71, 0x2F, 0x6F, 0x69,
+    0x63, 0x2F, 0x73, 0x65, 0x63, 0x2F, 0x64, 0x70, 0x61, 0x69, 0x72, 0x69, 0x6E, 0x67, 0x63, 0x72,
+    0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66, 0x60, 0x6A, 0x70, 0x65, 0x72, 0x6D,
+    0x69, 0x73, 0x73, 0x69, 0x6F, 0x6E, 0x06, 0xA3, 0x6B, 0x73, 0x75, 0x62, 0x6A, 0x65, 0x63, 0x74,
+    0x75, 0x75, 0x69, 0x64, 0x61, 0x2A, 0x69, 0x72, 0x65, 0x73, 0x6F, 0x75, 0x72, 0x63, 0x65, 0x73,
+    0x81, 0xA4, 0x64, 0x68, 0x72, 0x65, 0x66, 0x6C, 0x2F, 0x6F, 0x69, 0x63, 0x2F, 0x73, 0x65, 0x63,
+    0x2F, 0x76, 0x65, 0x72, 0x63, 0x72, 0x65, 0x6C, 0x60, 0x62, 0x72, 0x74, 0x60, 0x62, 0x69, 0x66,
+    0x60, 0x6A, 0x70, 0x65, 0x72, 0x6D, 0x69, 0x73, 0x73, 0x69, 0x6F, 0x6E, 0x02, 0x6A, 0x72, 0x6F,
+    0x77, 0x6E, 0x65, 0x72, 0x75, 0x75, 0x69, 0x64, 0x78, 0x24, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
+    0x32, 0x32, 0x2D, 0x32, 0x32, 0x32, 0x32, 0x2D, 0x32, 0x32, 0x32, 0x32, 0x2D, 0x32, 0x32, 0x32,
+    0x32, 0x2D, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x65, 0x70,
+    0x73, 0x74, 0x61, 0x74, 0x58, 0x79, 0xA7, 0x64, 0x69, 0x73, 0x6F, 0x70, 0xF4, 0x6A, 0x64, 0x65,
+    0x76, 0x69, 0x63, 0x65, 0x75, 0x75, 0x69, 0x64, 0x78, 0x24, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
+    0x32, 0x32, 0x2D, 0x32, 0x32, 0x32, 0x32, 0x2D, 0x32, 0x32, 0x32, 0x32, 0x2D, 0x32, 0x32, 0x32,
+    0x32, 0x2D, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x62, 0x63,
+    0x6D, 0x02, 0x62, 0x74, 0x6D, 0x00, 0x62, 0x6F, 0x6D, 0x03, 0x62, 0x73, 0x6D, 0x03, 0x6A, 0x72,
+    0x6F, 0x77, 0x6E, 0x65, 0x72, 0x75, 0x75, 0x69, 0x64, 0x78, 0x24, 0x32, 0x32, 0x32, 0x32, 0x32,
+    0x32, 0x32, 0x32, 0x2D, 0x32, 0x32, 0x32, 0x32, 0x2D, 0x32, 0x32, 0x32, 0x32, 0x2D, 0x32, 0x32,
+    0x32, 0x32, 0x2D, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x64,
+    0x64, 0x6F, 0x78, 0x6D, 0x58, 0xB6, 0xA8, 0x64, 0x6F, 0x78, 0x6D, 0x73, 0x81, 0x00, 0x66, 0x6F,
+    0x78, 0x6D, 0x73, 0x65, 0x6C, 0x00, 0x63, 0x73, 0x63, 0x74, 0x01, 0x65, 0x6F, 0x77, 0x6E, 0x65,
+    0x64, 0xF4, 0x6A, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x75, 0x75, 0x69, 0x64, 0x78, 0x24, 0x32,
+    0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x2D, 0x32, 0x32, 0x32, 0x32, 0x2D, 0x32, 0x32, 0x32,
+    0x32, 0x2D, 0x32, 0x32, 0x32, 0x32, 0x2D, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
+    0x32, 0x32, 0x32, 0x6C, 0x64, 0x65, 0x76, 0x6F, 0x77, 0x6E, 0x65, 0x72, 0x75, 0x75, 0x69, 0x64,
+    0x78, 0x24, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x2D, 0x30, 0x30, 0x30, 0x30, 0x2D,
+    0x30, 0x30, 0x30, 0x30, 0x2D, 0x30, 0x30, 0x30, 0x30, 0x2D, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
+    0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x6A, 0x72, 0x6F, 0x77, 0x6E, 0x65, 0x72, 0x75, 0x75, 0x69,
+    0x64, 0x78, 0x24, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x2D, 0x32, 0x32, 0x32, 0x32,
+    0x2D, 0x32, 0x32, 0x32, 0x32, 0x2D, 0x32, 0x32, 0x32, 0x32, 0x2D, 0x32, 0x32, 0x32, 0x32, 0x32,
+    0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x63, 0x64, 0x70, 0x63, 0xF5, 0xFF
+};
+
+/* Function that creates a new LED resource by calling the
+ * OCCreateResource() method.
+ */
+int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
+
+/* This method converts the payload to JSON format */
+OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
+
+/* Following methods process the PUT, GET, POST
+ * requests
+ */
+OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
+                                         OCRepPayload **payload);
+OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
+                                         OCRepPayload **payload);
+OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
+                                        OCEntityHandlerResponse *response,
+                                        OCRepPayload **payload);
+
+/* Entity Handler callback functions */
+OCEntityHandlerResult
+OCEntityHandlerCb (OCEntityHandlerFlag flag,
+        OCEntityHandlerRequest *entityHandlerRequest,
+        void* callbackParam);
+
+const char *getResult(OCStackResult result) {
+    switch (result) {
+    case OC_STACK_OK:
+        return "OC_STACK_OK";
+    case OC_STACK_RESOURCE_CREATED:
+        return "OC_STACK_RESOURCE_CREATED";
+    case OC_STACK_RESOURCE_DELETED:
+        return "OC_STACK_RESOURCE_DELETED";
+    case OC_STACK_INVALID_URI:
+        return "OC_STACK_INVALID_URI";
+    case OC_STACK_INVALID_QUERY:
+        return "OC_STACK_INVALID_QUERY";
+    case OC_STACK_INVALID_IP:
+        return "OC_STACK_INVALID_IP";
+    case OC_STACK_INVALID_PORT:
+        return "OC_STACK_INVALID_PORT";
+    case OC_STACK_INVALID_CALLBACK:
+        return "OC_STACK_INVALID_CALLBACK";
+    case OC_STACK_INVALID_METHOD:
+        return "OC_STACK_INVALID_METHOD";
+    case OC_STACK_NO_MEMORY:
+        return "OC_STACK_NO_MEMORY";
+    case OC_STACK_COMM_ERROR:
+        return "OC_STACK_COMM_ERROR";
+    case OC_STACK_INVALID_PARAM:
+        return "OC_STACK_INVALID_PARAM";
+    case OC_STACK_NOTIMPL:
+        return "OC_STACK_NOTIMPL";
+    case OC_STACK_NO_RESOURCE:
+        return "OC_STACK_NO_RESOURCE";
+    case OC_STACK_RESOURCE_ERROR:
+        return "OC_STACK_RESOURCE_ERROR";
+    case OC_STACK_SLOW_RESOURCE:
+        return "OC_STACK_SLOW_RESOURCE";
+    case OC_STACK_NO_OBSERVERS:
+        return "OC_STACK_NO_OBSERVERS";
+    #ifdef WITH_PRESENCE
+    case OC_STACK_PRESENCE_STOPPED:
+        return "OC_STACK_PRESENCE_STOPPED";
+    #endif
+    case OC_STACK_ERROR:
+        return "OC_STACK_ERROR";
+    default:
+        return "UNKNOWN";
+    }
+}
+
+OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
+{
+    OCRepPayload* payload = OCRepPayloadCreate();
+    if(!payload)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
+        return NULL;
+    }
+
+    OCRepPayloadSetUri(payload, uri);
+    OCRepPayloadSetPropBool(payload, "state", state);
+    OCRepPayloadSetPropInt(payload, "power", power);
+
+    return payload;
+}
+
+//This function takes the request as an input and returns the response
+OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
+{
+    if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+    {
+        OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
+        return NULL;
+    }
+
+    OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
+
+    LEDResource *currLEDResource = &LED;
+
+    if (ehRequest->resource == gLedInstance[0].handle)
+    {
+        currLEDResource = &gLedInstance[0];
+        gResourceUri = (char *) "/a/led/0";
+    }
+    else if (ehRequest->resource == gLedInstance[1].handle)
+    {
+        currLEDResource = &gLedInstance[1];
+        gResourceUri = (char *) "/a/led/1";
+    }
+
+    if(OC_REST_PUT == ehRequest->method)
+    {
+        // Get pointer to query
+        int64_t pow;
+        if(OCRepPayloadGetPropInt(input, "power", &pow))
+        {
+            currLEDResource->power =pow;
+        }
+
+        bool state;
+        if(OCRepPayloadGetPropBool(input, "state", &state))
+        {
+            currLEDResource->state = state;
+        }
+    }
+
+    return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
+}
+
+OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
+        OCRepPayload **payload)
+{
+    OCEntityHandlerResult ehResult;
+
+    OCRepPayload *getResp = constructResponse(ehRequest);
+
+    if(getResp)
+    {
+        *payload = getResp;
+        ehResult = OC_EH_OK;
+    }
+    else
+    {
+        ehResult = OC_EH_ERROR;
+    }
+
+    return ehResult;
+}
+
+OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
+        OCRepPayload **payload)
+{
+    OCEntityHandlerResult ehResult;
+
+    OCRepPayload *putResp = constructResponse(ehRequest);
+
+    if(putResp)
+    {
+        *payload = putResp;
+        ehResult = OC_EH_OK;
+    }
+    else
+    {
+        ehResult = OC_EH_ERROR;
+    }
+
+    return ehResult;
+}
+
+OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
+        OCEntityHandlerResponse *response, OCRepPayload **payload)
+{
+    OCRepPayload *respPLPost_led = NULL;
+    OCEntityHandlerResult ehResult = OC_EH_OK;
+
+    /*
+     * The entity handler determines how to process a POST request.
+     * Per the REST paradigm, POST can also be used to update representation of existing
+     * resource or create a new resource.
+     * In the sample below, if the POST is for /a/led then a new instance of the LED
+     * resource is created with default representation (if representation is included in
+     * POST payload it can be used as initial values) as long as the instance is
+     * lesser than max new instance count. Once max instance count is reached, POST on
+     * /a/led updated the representation of /a/led (just like PUT)
+     */
+
+    if (ehRequest->resource == LED.handle)
+    {
+        if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
+        {
+            // Create new LED instance
+            char newLedUri[15] = "/a/led/";
+            int newLedUriLength = strlen(newLedUri);
+            snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
+
+            respPLPost_led = OCRepPayloadCreate();
+            OCRepPayloadSetUri(respPLPost_led, gResourceUri);
+            OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
+
+            if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
+            {
+                OIC_LOG (INFO, TAG, "Created new LED instance");
+                gLedInstance[gCurrLedInstance].state = 0;
+                gLedInstance[gCurrLedInstance].power = 0;
+                gCurrLedInstance++;
+                strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
+                ehResult = OC_EH_RESOURCE_CREATED;
+            }
+        }
+        else
+        {
+            respPLPost_led = constructResponse(ehRequest);
+        }
+    }
+    else
+    {
+        for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
+        {
+            if (ehRequest->resource == gLedInstance[i].handle)
+            {
+                if (i == 0)
+                {
+                    respPLPost_led = constructResponse(ehRequest);
+                    break;
+                }
+                else if (i == 1)
+                {
+                    respPLPost_led = constructResponse(ehRequest);
+                }
+            }
+        }
+    }
+
+    if (respPLPost_led != NULL)
+    {
+        *payload = respPLPost_led;
+        ehResult = OC_EH_OK;
+    }
+    else
+    {
+        OIC_LOG_V (INFO, TAG, "Payload was NULL");
+        ehResult = OC_EH_ERROR;
+    }
+
+    return ehResult;
+}
+
+OCEntityHandlerResult
+OCEntityHandlerCb (OCEntityHandlerFlag flag,
+        OCEntityHandlerRequest *entityHandlerRequest,
+        void* callbackParam)
+{
+    OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
+    (void)callbackParam;
+    OCEntityHandlerResult ehResult = OC_EH_ERROR;
+
+    OCEntityHandlerResponse response;
+    memset(&response, 0, sizeof(response));
+
+    // Validate pointer
+    if (!entityHandlerRequest)
+    {
+        OIC_LOG (ERROR, TAG, "Invalid request pointer");
+        return OC_EH_ERROR;
+    }
+
+    OCRepPayload* payload = NULL;
+
+    if (flag & OC_REQUEST_FLAG)
+    {
+        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        if (entityHandlerRequest)
+        {
+            if (OC_REST_GET == entityHandlerRequest->method)
+            {
+                OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
+                ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
+            }
+            else if (OC_REST_PUT == entityHandlerRequest->method)
+            {
+                OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
+                ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
+            }
+            else if (OC_REST_POST == entityHandlerRequest->method)
+            {
+                OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
+                ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
+            }
+            else
+            {
+                OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+                        entityHandlerRequest->method);
+                ehResult = OC_EH_ERROR;
+            }
+
+            if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
+            {
+                // Format the response.  Note this requires some info about the request
+                response.requestHandle = entityHandlerRequest->requestHandle;
+                response.resourceHandle = entityHandlerRequest->resource;
+                response.ehResult = ehResult;
+                response.payload = (OCPayload*)(payload);
+                response.numSendVendorSpecificHeaderOptions = 0;
+                memset(response.sendVendorSpecificHeaderOptions, 0,
+                       sizeof(response.sendVendorSpecificHeaderOptions));
+                memset(response.resourceUri, 0, sizeof(response.resourceUri));
+                // Indicate that response is NOT in a persistent buffer
+                response.persistentBufferFlag = 0;
+
+                // Send the response
+                if (OCDoResponse(&response) != OC_STACK_OK)
+                {
+                    OIC_LOG(ERROR, TAG, "Error sending response");
+                    ehResult = OC_EH_ERROR;
+                }
+            }
+        }
+    }
+
+    OCPayloadDestroy(response.payload);
+    return ehResult;
+}
+
+/* SIGINT handler: set gQuitFlag to 1 for graceful termination */
+void handleSigInt(int signum)
+{
+    if (signum == SIGINT)
+    {
+        gQuitFlag = 1;
+    }
+}
+
+static void GetCurrentWorkingDirectory(char* buf, size_t bufsize)
+{
+    char cwd[1024] = {0};
+    const char* unittest_path = "resource/csdk/security/provisioning/unittest";
+    if(getcwd(cwd, sizeof(cwd)) != NULL)
+    {
+        if(strstr(cwd, unittest_path) == NULL)
+        {
+#if defined __linux__
+#if __x86_64__
+        snprintf(buf, bufsize, "%s/out/linux/x86_64/release/%s/", cwd, unittest_path);
+        snprintf(buf, bufsize, "%s/out/linux/x86_64/release/%s/", cwd, unittest_path);
+#else
+        snprintf(buf, bufsize, "%s/out/linux/x86/release/%s/", cwd, unittest_path);
+        snprintf(buf, bufsize, "%s/out/linux/x86/release/%s/", cwd, unittest_path);
+#endif //__x86_64__
+#endif //defined __linux__
+        }
+        else
+        {
+            snprintf(buf, bufsize, "%s/", cwd);
+        }
+    }
+}
+
+FILE* server_fopen(const char *path, const char *mode)
+{
+    (void)path;
+    char cwd[1024] = {0};
+    char cred_path[1024] = {0};
+    GetCurrentWorkingDirectory(cwd, sizeof(cwd));
+    snprintf(cred_path, sizeof(cred_path), "%s%s", cwd, CRED_FILE);
+    return fopen(cred_path, mode);
+}
+
+int main()
+{
+    struct timespec timeout;
+
+    //Delete previous SVR DB, if exist.
+    char cwd[1024] = {0};
+    char cred_path[1024] = {0};
+    char del_cmd[1024] = {0};
+    FILE* fp = NULL;
+    GetCurrentWorkingDirectory(cwd, sizeof(cwd));
+    snprintf(del_cmd, sizeof(del_cmd), "rm -rf %s%s", cwd, CRED_FILE);
+    system(del_cmd);
+
+    //Generate default SVR DB.
+    snprintf(cred_path, sizeof(cred_path), "%s%s", cwd, CRED_FILE);
+    fp = fopen(cred_path, "w");
+    if(NULL != fp)
+    {
+        size_t numberItems = fwrite(DEFAULT_SVR_DB, 1, sizeof(DEFAULT_SVR_DB), fp);
+        if(sizeof(DEFAULT_SVR_DB) != numberItems)
+        {
+            OIC_LOG_V(ERROR, TAG, "Failed to initialize SVR DB (%s)", cred_path);
+            fclose(fp);
+            return -1;
+        }
+        fclose(fp);
+    }
+
+    OIC_LOG(DEBUG, TAG, "OCServer is starting...");
+
+    // Initialize Persistent Storage for SVR database
+    OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
+
+    OCRegisterPersistentStorageHandler(&ps);
+
+    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "OCStack init error");
+        return 0;
+    }
+
+    /*
+     * Declare and create the example resource: LED
+     */
+    createLEDResource(gResourceUri, &LED, false, 0);
+
+    timeout.tv_sec  = 0;
+    timeout.tv_nsec = 100000000L;
+
+    // Break from loop with Ctrl-C
+    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    signal(SIGINT, handleSigInt);
+    while (!gQuitFlag)
+    {
+        if (OCProcess() != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG, "OCStack process error");
+            return 0;
+        }
+        nanosleep(&timeout, NULL);
+    }
+
+    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+
+    if (OCStop() != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "OCStack process error");
+    }
+
+    return 0;
+}
+
+int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
+{
+    if (!uri)
+    {
+        OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
+        return -1;
+    }
+
+    ledResource->state = resourceState;
+    ledResource->power= resourcePower;
+    OCStackResult res = OCCreateResource(&(ledResource->handle),
+            "core.led",
+            OC_RSRVD_INTERFACE_DEFAULT,
+            uri,
+            OCEntityHandlerCb,
+            NULL,
+            OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
+    OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
+
+    return 0;
+}
index d2b9f4b..9537efc 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifdef WITH_ARDUINO
+#ifdef HAVE_STRING_H
 #include <string.h>
-#else
+#elif HAVE_STRINGS_H
 #include <strings.h>
 #endif
 #include <stdlib.h>
 
+#include "utlist.h"
 #include "ocstack.h"
+#include "octypes.h"
 #include "ocserverrequest.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
@@ -45,6 +47,7 @@
 #define TAG  "SRM-ACL"
 #define NUMBER_OF_SEC_PROV_RSCS 4
 #define NUMBER_OF_DEFAULT_SEC_RSCS 2
+#define STRING_UUID_SIZE (UUID_LENGTH * 2 + 5)
 
 static const uint8_t ACL_MAP_SIZE = 2;
 static const uint8_t ACL_ACLIST_MAP_SIZE = 1;
@@ -59,60 +62,205 @@ static OicSecAcl_t *gAcl = NULL;
 static OCResourceHandle gAclHandle = NULL;
 
 /**
+ * This function frees OicSecRsrc_t object's fields and object itself.
+ */
+static void FreeRsrc(OicSecRsrc_t *rsrc)
+{
+    //Clean each member of resource
+    OICFree(rsrc->href);
+    OICFree(rsrc->rel);
+    //Clean "rt"
+    if(0 < rsrc->typeLen && rsrc->types)
+    {
+        for(size_t i = 0; i < rsrc->typeLen; i++)
+        {
+            OICFree(rsrc->types[i]);
+        }
+        OICFree(rsrc->types);
+        rsrc->types = NULL;
+    }
+    //Clean "if"
+    if(0 < rsrc->interfaceLen && rsrc->interfaces)
+    {
+        for(size_t i = 0; i < rsrc->interfaceLen; i++)
+        {
+            OICFree(rsrc->interfaces[i]);
+        }
+        OICFree(rsrc->interfaces);
+        rsrc->interfaces = NULL;
+    }
+    OICFree(rsrc);
+    rsrc = NULL;
+}
+
+/**
  * This function frees OicSecAcl_t object's fields and object itself.
  */
-static void FreeACE(OicSecAcl_t *ace)
+static void FreeACE(OicSecAce_t *ace)
 {
-    size_t i;
     if (NULL == ace)
     {
         OIC_LOG(ERROR, TAG, "Invalid Parameter");
         return;
     }
 
-    // Clean Resources
-    for (i = 0; i < ace->resourcesLen; i++)
+    //Clean Resources
+    OicSecRsrc_t* rsrc = NULL;
+    OicSecRsrc_t* tmpRsrc = NULL;
+    LL_FOREACH_SAFE(ace->resources, rsrc, tmpRsrc)
     {
-        OICFree(ace->resources[i]);
+        LL_DELETE(ace->resources, rsrc);
+        FreeRsrc(rsrc);
     }
-    OICFree(ace->resources);
 
-    //Clean Period
-    if (ace->periods)
+    //Clean Validities
+    OicSecValidity_t *validity = NULL;
+    OicSecValidity_t *tmpValidity = NULL;
+    LL_FOREACH_SAFE(ace->validities, validity, tmpValidity)
     {
-        for (i = 0; i < ace->prdRecrLen; i++)
-        {
-            OICFree(ace->periods[i]);
-        }
-        OICFree(ace->periods);
-    }
+        LL_DELETE(ace->validities, validity);
 
-    //Clean Recurrence
-    if (ace->recurrences)
-    {
-        for (i = 0; i < ace->prdRecrLen; i++)
+        //Clean period
+        OICFree(validity->period);
+
+        //Clean recurrence
+        for(size_t i = 0; i < validity->recurrenceLen; i++)
         {
-            OICFree(ace->recurrences[i]);
+            OICFree(validity->recurrences[i]);
         }
-        OICFree(ace->recurrences);
+        OICFree(validity->recurrences);
+        OICFree(validity);
+        validity = NULL;
     }
 
-    // Clean ACL node itself
+    //Clean ACE
     OICFree(ace);
+    ace = NULL;
 }
 
 void DeleteACLList(OicSecAcl_t* acl)
 {
     if (acl)
     {
-        OicSecAcl_t *aclTmp1 = NULL;
-        OicSecAcl_t *aclTmp2 = NULL;
-        LL_FOREACH_SAFE(acl, aclTmp1, aclTmp2)
+        OicSecAce_t *ace = NULL;
+        OicSecAce_t *tmpAce = NULL;
+        LL_FOREACH_SAFE(acl->aces, ace, tmpAce)
         {
-            LL_DELETE(acl, aclTmp1);
-            FreeACE(aclTmp1);
+            LL_DELETE(acl->aces, ace);
+            FreeACE(ace);
+        }
+        acl->aces = NULL;
+        OICFree(acl);
+    }
+}
+
+OicSecAce_t* DuplicateACE(const OicSecAce_t* ace)
+{
+    OicSecAce_t* newAce = NULL;
+    size_t allocateSize = 0;
+
+    if(ace)
+    {
+        newAce = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+        VERIFY_NON_NULL(TAG, newAce, ERROR);
+
+        //Subject uuid
+        memcpy(&newAce->subjectuuid, &ace->subjectuuid, sizeof(OicUuid_t));
+
+        OicSecRsrc_t* rsrc = NULL;
+        LL_FOREACH(ace->resources, rsrc)
+        {
+            OicSecRsrc_t* newRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+            VERIFY_NON_NULL(TAG, newRsrc, ERROR);
+            LL_APPEND(newAce->resources, newRsrc);
+
+            //href is mandatory
+            VERIFY_NON_NULL(TAG, rsrc->href, ERROR);
+            allocateSize = strlen(rsrc->href) + 1;
+            newRsrc->href = (char*)OICMalloc(sizeof(char) * allocateSize);
+            VERIFY_NON_NULL(TAG, newRsrc->href, ERROR);
+            OICStrcpy(newRsrc->href, allocateSize, rsrc->href);
+
+            if(rsrc->rel)
+            {
+                allocateSize = strlen(rsrc->rel) + 1;
+                newRsrc->rel = (char*)OICMalloc(sizeof(char) * allocateSize);
+                VERIFY_NON_NULL(TAG, newRsrc->rel, ERROR);
+                OICStrcpy(newRsrc->rel, allocateSize, rsrc->rel);
+            }
+
+            if(rsrc->types && 0 < rsrc->typeLen)
+            {
+                newRsrc->typeLen = rsrc->typeLen;
+                newRsrc->types = (char**)OICCalloc(rsrc->typeLen, sizeof(char*));
+                VERIFY_NON_NULL(TAG, (newRsrc->types), ERROR);
+                for(size_t i = 0; i < rsrc->typeLen; i++)
+                {
+                    newRsrc->types[i] = OICStrdup(rsrc->types[i]);
+                    VERIFY_NON_NULL(TAG, (newRsrc->types[i]), ERROR);
+                }
+            }
+
+            if(rsrc->interfaces && 0 < rsrc->interfaceLen)
+            {
+                newRsrc->interfaceLen = rsrc->interfaceLen;
+                newRsrc->interfaces = (char**)OICCalloc(rsrc->interfaceLen, sizeof(char*));
+                VERIFY_NON_NULL(TAG, (newRsrc->interfaces), ERROR);
+                for(size_t i = 0; i < rsrc->interfaceLen; i++)
+                {
+                    newRsrc->interfaces[i] = OICStrdup(rsrc->interfaces[i]);
+                    VERIFY_NON_NULL(TAG, (newRsrc->interfaces[i]), ERROR);
+                }
+            }
+        }
+
+        //Permission
+        newAce->permission = ace->permission;
+
+        //Validity
+        if(ace->validities)
+        {
+            OicSecValidity_t* validity = NULL;
+            LL_FOREACH(ace->validities, validity)
+            {
+                OicSecValidity_t* newValidity = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+                VERIFY_NON_NULL(TAG, newValidity, ERROR);
+                LL_APPEND(newAce->validities, newValidity);
+
+                if(validity->period)
+                {
+                    allocateSize = strlen(validity->period) + 1;
+                    newValidity->period = (char*)OICMalloc(sizeof(char) * allocateSize);
+                    VERIFY_NON_NULL(TAG, newValidity->period, ERROR);
+                    OICStrcpy(newValidity->period, allocateSize, validity->period);
+                }
+
+                if(validity->recurrences && 0 < validity->recurrenceLen)
+                {
+                    newValidity->recurrenceLen = validity->recurrenceLen;
+
+                    newValidity->recurrences = (char**)OICMalloc(sizeof(char*) * validity->recurrenceLen);
+                    VERIFY_NON_NULL(TAG, newValidity->recurrences, ERROR);
+
+                    for(size_t i = 0; i < validity->recurrenceLen; i++)
+                    {
+                        allocateSize = strlen(validity->recurrences[i]) + 1;
+                        newValidity->recurrences[i] = (char*)OICMalloc(sizeof(char) * allocateSize);
+                        VERIFY_NON_NULL(TAG, (newValidity->recurrences[i]), ERROR);
+                        OICStrcpy(newValidity->recurrences[i], allocateSize, validity->recurrences[i]);
+                    }
+                }
+            }
         }
+
+        newAce->next = NULL;
     }
+
+    return newAce;
+
+exit:
+    FreeACE(newAce);
+    return NULL;
 }
 
 static size_t OicSecAclSize(const OicSecAcl_t *secAcl)
@@ -121,12 +269,12 @@ static size_t OicSecAclSize(const OicSecAcl_t *secAcl)
     {
         return 0;
     }
-    OicSecAcl_t *acl = (OicSecAcl_t *)secAcl;
+    OicSecAce_t *ace= (OicSecAce_t *)secAcl->aces;
     size_t size = 0;
-    while (acl)
+    while (ace)
     {
        size++;
-       acl = acl->next;
+       ace = ace->next;
     }
     return size;
 }
@@ -141,6 +289,7 @@ OCStackResult AclToCBORPayload(const OicSecAcl_t *secAcl, uint8_t **payload, siz
     OCStackResult ret = OC_STACK_ERROR;
     CborError cborEncoderResult = CborNoError;
     OicSecAcl_t *acl = (OicSecAcl_t *)secAcl;
+    OicSecAce_t* ace = NULL;
     CborEncoder encoder;
     CborEncoder aclMap;
     CborEncoder aclListMap;
@@ -179,21 +328,25 @@ OCStackResult AclToCBORPayload(const OicSecAcl_t *secAcl, uint8_t **payload, siz
     cborEncoderResult = cbor_encoder_create_array(&aclListMap, &acesArray, OicSecAclSize(secAcl));
     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating ACES Array.");
 
-    while (acl)
+    ace = NULL;
+    LL_FOREACH (acl->aces, ace)
     {
         CborEncoder oicSecAclMap;
         // ACL Map size - Number of mandatory items
         uint8_t aclMapSize = ACL_ACES_MAP_SIZE;
         size_t inLen = 0;
 
-        // Create ACL Map
-        if (acl->periods)
+        OicSecValidity_t* validityElts = ace->validities;
+        while(validityElts)
         {
-            ++aclMapSize;
-        }
-        if (acl->recurrences)
-        {
-            ++aclMapSize;
+            if(validityElts->period)
+            {
+                aclMapSize++;
+            }
+            if(validityElts->recurrences)
+            {
+                aclMapSize++;
+            }
         }
 
         cborEncoderResult = cbor_encoder_create_map(&acesArray, &oicSecAclMap, aclMapSize);
@@ -203,7 +356,7 @@ OCStackResult AclToCBORPayload(const OicSecAcl_t *secAcl, uint8_t **payload, siz
         cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_SUBJECTID_NAME,
             strlen(OIC_JSON_SUBJECTID_NAME));
         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Name Tag.");
-        inLen = (memcmp(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0) ?
+        inLen = (memcmp(&(ace->subjectuuid), &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0) ?
             WILDCARD_SUBJECT_ID_LEN : sizeof(OicUuid_t);
         if(inLen == WILDCARD_SUBJECT_ID_LEN)
         {
@@ -214,10 +367,10 @@ OCStackResult AclToCBORPayload(const OicSecAcl_t *secAcl, uint8_t **payload, siz
         else
         {
             char *subject = NULL;
-            ret = ConvertUuidToStr(&acl->subject, &subject);
+            ret = ConvertUuidToStr(&ace->subjectuuid, &subject);
             VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
             cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, subject, strlen(subject));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Subject Id Value.");
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Subject UUID Value.");
             OICFree(subject);
         }
 
@@ -228,112 +381,168 @@ OCStackResult AclToCBORPayload(const OicSecAcl_t *secAcl, uint8_t **payload, siz
                 strlen(OIC_JSON_RESOURCES_NAME));
             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Tag.");
 
-            cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &resources, acl->resourcesLen);
+            size_t rsrcLen = 0;
+            OicSecRsrc_t* rsrcElts = NULL;
+            LL_FOREACH(ace->resources, rsrcElts)
+            {
+                rsrcLen++;
+            }
+
+            cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &resources, rsrcLen);
             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Array.");
 
-            for (size_t i = 0; i < acl->resourcesLen; i++)
+            OicSecRsrc_t* rsrc = NULL;
+            LL_FOREACH(ace->resources, rsrc)
             {
 
                 CborEncoder rMap;
                 cborEncoderResult = cbor_encoder_create_map(&resources, &rMap, ACL_RESOURCE_MAP_SIZE);
                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Resource Map.");
 
+                //href -- Mandatory
+                VERIFY_NON_NULL(TAG, rsrc->href, ERROR);
                 cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_HREF_NAME,
                         strlen(OIC_JSON_HREF_NAME));
                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding HREF Name Tag.");
-                cborEncoderResult = cbor_encode_text_string(&rMap, acl->resources[i],
-                        strlen(acl->resources[i]));
+                cborEncoderResult = cbor_encode_text_string(&rMap, rsrc->href, strlen(rsrc->href));
                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding HREF Value in Map.");
 
-                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_REL_NAME,
-                        strlen(OIC_JSON_REL_NAME));
-                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Name Tag.");
-
-                // TODO : Need to assign real value of REL
-                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
-                        strlen(OIC_JSON_EMPTY_STRING));
-                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Value.");
-
+                //resource type -- Mandatory
                 cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_RT_NAME,
                         strlen(OIC_JSON_RT_NAME));
                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
 
-                // TODO : Need to assign real value of RT
-                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
-                        strlen(OIC_JSON_EMPTY_STRING));
-                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
+                CborEncoder resourceTypes;
+                cborEncoderResult = cbor_encoder_create_array(&rMap, &resourceTypes, rsrc->typeLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Array.");
+                for(size_t i = 0; i < rsrc->typeLen; i++)
+                {
+                    cborEncoderResult = cbor_encode_text_string(&resourceTypes, rsrc->types[i], strlen(rsrc->types[i]));
+                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
+                }
+                cborEncoderResult = cbor_encoder_close_container(&rMap, &resourceTypes);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing resourceTypes.");
 
+                //interface -- Mandatory
                 cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_IF_NAME,
                         strlen(OIC_JSON_IF_NAME));
                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
 
-                // TODO : Need to assign real value of IF
-                cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
-                        strlen(OIC_JSON_EMPTY_STRING));
-                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
+                CborEncoder interfaces;
+                cborEncoderResult = cbor_encoder_create_array(&rMap, &interfaces, rsrc->interfaceLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Array.");
+                for(size_t i = 0; i < rsrc->interfaceLen; i++)
+                {
+                    cborEncoderResult = cbor_encode_text_string(&interfaces, rsrc->interfaces[i], strlen(rsrc->interfaces[i]));
+                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
+                }
+                cborEncoderResult = cbor_encoder_close_container(&rMap, &interfaces);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing interfaces.");
 
+                //rel
+                if(rsrc->rel)
+                {
+                    cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_REL_NAME,
+                            strlen(OIC_JSON_REL_NAME));
+                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Name Tag.");
+                    cborEncoderResult = cbor_encode_text_string(&rMap, rsrc->rel, strlen(rsrc->rel));
+                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Value.");
+                }
+                else
+                {
+                    cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_REL_NAME,
+                            strlen(OIC_JSON_REL_NAME));
+                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Name Tag.");
+                    cborEncoderResult = cbor_encode_text_string(&rMap, "", 0);
+                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Value.");
+                }
 
                 cborEncoderResult = cbor_encoder_close_container(&resources, &rMap);
                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Map.");
-
             }
             cborEncoderResult = cbor_encoder_close_container(&oicSecAclMap, &resources);
             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Name Array.");
         }
 
-
         // Permissions -- Mandatory
         cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_PERMISSION_NAME,
             strlen(OIC_JSON_PERMISSION_NAME));
         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Permission Name Tag.");
-        cborEncoderResult = cbor_encode_int(&oicSecAclMap, acl->permission);
+        cborEncoderResult = cbor_encode_int(&oicSecAclMap, ace->permission);
         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Permission Name Value.");
 
-        // Period -- Not Mandatory
-        if (acl->periods)
+        // TODO: Need to verfication for validity
+        // Validity(Time-interval) -- Not Mandatory
+        if(ace->validities)
         {
-
-            CborEncoder period;
-            cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_PERIOD_NAME,
-                strlen(OIC_JSON_PERIOD_NAME));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Tag.");
-            cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &period, acl->prdRecrLen);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Array.");
-            for (size_t i = 0; i < acl->prdRecrLen; i++)
+            size_t validityLen = 0;
+            validityElts = NULL;
+            LL_FOREACH(ace->validities, validityElts)
             {
-                cborEncoderResult = cbor_encode_text_string(&period, acl->periods[i],
-                    strlen(acl->periods[i]));
-                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Value in Array.");
+                validityLen++;
             }
-            cborEncoderResult = cbor_encoder_close_container(&oicSecAclMap, &period);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Period Array.");
-        }
 
-        // Recurrence -- Not Mandatory
-        if (acl->recurrences)
-        {
-            CborEncoder recurrences;
-            cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_RECURRENCES_NAME,
-                strlen(OIC_JSON_RECURRENCES_NAME));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Tag.");
-            cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &recurrences, acl->prdRecrLen);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array.");
-
-            for (size_t i = 0; i < acl->prdRecrLen; i++)
+            CborEncoder validities;
+            cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_VALIDITY_NAME,
+                strlen(OIC_JSON_VALIDITY_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Validity Tag.");
+            cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &validities, validityLen);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Validities Array.");
+
+            //How to add the value w/o "title" using tinycobr...? :(
+
+            validityElts = NULL;
+            LL_FOREACH(ace->validities, validityElts)
             {
-                cborEncoderResult = cbor_encode_text_string(&recurrences, acl->recurrences[i],
-                    strlen(acl->recurrences[i]));
-                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array Value.");
+                 CborEncoder validity;
+                 size_t validitySize = 0;
+                 if(validityElts->period)
+                {
+                    validitySize++;
+                }
+                if(validityElts->recurrences)
+                {
+                    validitySize++;
+                }
+
+                cborEncoderResult = cbor_encoder_create_array(&validities, &validity, validitySize);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Validity Array.");
+
+                // Period
+                if (validityElts->period)
+                {
+                    cborEncoderResult = cbor_encode_text_string(&validity, validityElts->period,
+                        strlen(validityElts->period));
+                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Value.");
+                }
+
+                // Recurrence
+                if (validityElts->recurrences)
+                {
+                    CborEncoder recurrences;
+                    cborEncoderResult = cbor_encoder_create_array(&validity, &recurrences, validityElts->recurrenceLen);
+                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array.");
+
+                    for (size_t i = 0; i < validityElts->recurrenceLen; i++)
+                    {
+                        cborEncoderResult = cbor_encode_text_string(&recurrences, validityElts->recurrences[i],
+                            strlen(validityElts->recurrences[i]));
+                        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array Value.");
+                    }
+                    cborEncoderResult = cbor_encoder_close_container(&validity, &recurrences);
+                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Recurrence Array");
+                }
+
+                cborEncoderResult = cbor_encoder_close_container(&validities, &validity);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Validity Array.");
             }
-            cborEncoderResult = cbor_encoder_close_container(&oicSecAclMap, &recurrences);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Recurrence Array");
 
+            cborEncoderResult = cbor_encoder_close_container(&oicSecAclMap, &validities);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Validities Array.");
         }
 
-
         cborEncoderResult = cbor_encoder_close_container(&acesArray, &oicSecAclMap);
         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACES Map.");
-        acl = acl->next;
     }
 
     // Close ACES Array
@@ -409,7 +618,7 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
     CborError cborFindResult = CborNoError;
     cbor_parser_init(cborPayload, size, 0, &parser, &aclCbor);
 
-    OicSecAcl_t *headAcl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    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 };
@@ -441,62 +650,51 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
                 while (cbor_value_is_valid(&aclistMap))
                 {
                     char* acName = NULL;
-                    size_t acLen = 0;
+                    size_t readLen = 0;
                     CborType acType = cbor_value_get_type(&aclistMap);
                     if (acType == CborTextStringType)
                     {
-                        cborFindResult = cbor_value_dup_text_string(&aclistMap, &acName, &acLen, NULL);
+                        cborFindResult = cbor_value_dup_text_string(&aclistMap, &acName, &readLen, NULL);
                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in ACLIST Map.");
                         cborFindResult = cbor_value_advance(&aclistMap);
                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in ACLIST Map.");
                     }
+
                     if(acName)
                     {
                         if (strcmp(acName, OIC_JSON_ACES_NAME)  == 0)
                         {
-
                             // Enter ACES Array
-                            CborValue aclArray = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
-                            cborFindResult = cbor_value_enter_container(&aclistMap, &aclArray);
-                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACL Array.");
+                            CborValue acesArray = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
+                            cborFindResult = cbor_value_enter_container(&aclistMap, &acesArray);
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACES Array.");
 
                             int acesCount = 0;
-                            while (cbor_value_is_valid(&aclArray))
+                            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.");
 
-                                CborValue aclMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
-                                cborFindResult = cbor_value_enter_container(&aclArray, &aclMap);
-                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACL Map.");
-                                OicSecAcl_t *acl = NULL;
+                                OicSecAce_t *ace = NULL;
+                                ace = (OicSecAce_t *) OICCalloc(1, sizeof(OicSecAce_t));
+                                VERIFY_NON_NULL(TAG, ace, ERROR);
+                                LL_APPEND(acl->aces, ace);
 
-                                if(acesCount == 1)
-                                {
-                                    acl = headAcl;
-                                }
-                                else
-                                {
-                                    acl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
-                                    OicSecAcl_t *temp = headAcl;
-                                    while (temp->next)
-                                    {
-                                        temp = temp->next;
-                                    }
-                                    temp->next = acl;
-                                }
                                 VERIFY_NON_NULL(TAG, acl, ERROR);
 
-                                while (cbor_value_is_valid(&aclMap))
+                                while (cbor_value_is_valid(&aceMap))
                                 {
                                     char* name = NULL;
                                     size_t len = 0;
-                                    CborType type = cbor_value_get_type(&aclMap);
+                                    CborType type = cbor_value_get_type(&aceMap);
                                     if (type == CborTextStringType)
                                     {
-                                        cborFindResult = cbor_value_dup_text_string(&aclMap, &name, &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.");
+                                        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)
                                     {
@@ -504,15 +702,15 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
                                         if (strcmp(name, OIC_JSON_SUBJECTID_NAME)  == 0)
                                         {
                                             char *subject = NULL;
-                                            cborFindResult = cbor_value_dup_text_string(&aclMap, &subject, &len, 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)
                                             {
-                                                acl->subject.id[0] = '*';
+                                                ace->subjectuuid.id[0] = '*';
                                             }
                                             else
                                             {
-                                                ret = ConvertStrToUuid(subject, &acl->subject);
+                                                ret = ConvertStrToUuid(subject, &ace->subjectuuid);
                                                 VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
                                             }
                                             OICFree(subject);
@@ -522,14 +720,9 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
                                         if (strcmp(name, OIC_JSON_RESOURCES_NAME) == 0)
                                         {
                                             CborValue resources = { .parser = NULL };
-                                            cborFindResult = cbor_value_get_array_length(&aclMap, &acl->resourcesLen);
-                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Resource Array Len Value.");
-                                            cborFindResult = cbor_value_enter_container(&aclMap, &resources);
+                                            cborFindResult = cbor_value_enter_container(&aceMap, &resources);
                                             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering a Resource Array.");
 
-                                            acl->resources = (char **) OICMalloc(acl->resourcesLen * sizeof(char*));
-                                            VERIFY_NON_NULL(TAG, acl->resources, ERROR);
-                                            int i = 0;
                                             while (cbor_value_is_valid(&resources))
                                             {
                                                 // rMap
@@ -537,6 +730,9 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
                                                 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))
                                                 {
@@ -550,37 +746,61 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
                                                     // "href"
                                                     if (0 == strcmp(OIC_JSON_HREF_NAME, rMapName))
                                                     {
-                                                        // TODO : Need to check data structure of OicSecAcl_t based on RAML spec.
-                                                        cborFindResult = cbor_value_dup_text_string(&rMap, &acl->resources[i++], &len, NULL);
+                                                        cborFindResult = cbor_value_dup_text_string(&rMap, &rsrc->href, &len, NULL);
                                                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Href Value.");
                                                     }
-                                                    // "rel"
-                                                    if (0 == strcmp(OIC_JSON_REL_NAME, rMapName))
-                                                    {
-                                                        // TODO : Need to check data structure of OicSecAcl_t based on RAML spec.
-                                                        char *relData = NULL;
-                                                        cborFindResult = cbor_value_dup_text_string(&rMap, &relData, &len, NULL);
-                                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding REL Value.");
-                                                        OICFree(relData);
-                                                    }
+
                                                     // "rt"
-                                                    if (0 == strcmp(OIC_JSON_RT_NAME, rMapName))
+                                                    if (0 == strcmp(OIC_JSON_RT_NAME, rMapName) && cbor_value_is_array(&rMap))
                                                     {
-                                                        // TODO : Need to check data structure of OicSecAcl_t and assign based on RAML spec.
-                                                        char *rtData = NULL;
-                                                        cborFindResult = cbor_value_dup_text_string(&rMap, &rtData, &len, NULL);
-                                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RT Value.");
-                                                        OICFree(rtData);
+                                                        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++)
+                                                        {
+                                                            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))
+                                                    if (0 == strcmp(OIC_JSON_IF_NAME, rMapName) && cbor_value_is_array(&rMap))
                                                     {
-                                                        // TODO : Need to check data structure of OicSecAcl_t and assign based on RAML spec.
-                                                        char *ifData = NULL;
-                                                        cborFindResult = cbor_value_dup_text_string(&rMap, &ifData, &len, NULL);
-                                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding IF Value.");
-                                                        OICFree(ifData);
+                                                        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++)
+                                                        {
+                                                            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))
@@ -602,65 +822,77 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
                                         // Permissions -- Mandatory
                                         if (strcmp(name, OIC_JSON_PERMISSION_NAME) == 0)
                                         {
-                                            cborFindResult = cbor_value_get_uint64(&aclMap, (uint64_t *) &acl->permission);
+                                            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;
                                         }
 
-                                        // Period -- Not mandatory
-                                        if (strcmp(name, OIC_JSON_PERIOD_NAME) == 0)
+                                        // TODO: Need to verfication for validity
+                                        // Validity -- Not mandatory
+                                        if(strcmp(name, OIC_JSON_VALIDITY_NAME) == 0)
                                         {
-                                            CborValue period = { .parser = NULL };
-                                            cborFindResult = cbor_value_get_array_length(&aclMap, &acl->prdRecrLen);
-                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Len.");
-                                            cborFindResult = cbor_value_enter_container(&aclMap, &period);
-                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Map.");
-                                            acl->periods = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
-                                            VERIFY_NON_NULL(TAG, acl->periods, ERROR);
-                                            int i = 0;
-                                            while (cbor_value_is_text_string(&period))
-                                            {
-                                                cborFindResult = cbor_value_dup_text_string(&period, &acl->periods[i++],
-                                                    &len, NULL);
-                                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Value.");
-                                                cborFindResult = cbor_value_advance(&period);
-                                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing a Period Array.");
-                                            }
-                                        }
+                                            CborValue validitiesMap = {.parser = NULL};
+                                            size_t validitySize = 0;
 
-                                        // Recurrence -- Not mandatory
-                                        if (strcmp(name, OIC_JSON_RECURRENCES_NAME) == 0)
-                                        {
-                                            CborValue recurrences = { .parser = NULL };
-                                            cborFindResult = cbor_value_enter_container(&aclMap, &recurrences);
-                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Recurrence Array.");
-                                            acl->recurrences = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
-                                            VERIFY_NON_NULL(TAG, acl->recurrences, ERROR);
-                                            int i = 0;
-                                            while (cbor_value_is_text_string(&recurrences))
+                                            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))
                                             {
-                                                cborFindResult = cbor_value_dup_text_string(&recurrences,
-                                                    &acl->recurrences[i++], &len, NULL);
-                                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Recurrence Array Value.");
-                                                cborFindResult = cbor_value_advance(&recurrences);
-                                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Closing Recurrence Array.");
+                                                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(&aclMap))
+                                    if (type != CborMapType && cbor_value_is_valid(&aceMap))
                                     {
-                                        cborFindResult = cbor_value_advance(&aclMap);
+                                        cborFindResult = cbor_value_advance(&aceMap);
                                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing the Array.");
                                     }
                                 }
 
-                                acl->next = NULL;
-
-                                if (cbor_value_is_valid(&aclArray))
+                                if (cbor_value_is_valid(&acesArray))
                                 {
-                                    cborFindResult = cbor_value_advance(&aclArray);
+                                    cborFindResult = cbor_value_advance(&acesArray);
                                     VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing ACL Array.");
                                 }
                             }
@@ -676,13 +908,13 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
                 }
             }
 
-            // TODO : Need to modify headAcl->owners[0].id to headAcl->rowner based on RAML spec.
+            //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.");
-                ret = ConvertStrToUuid(stRowner, &headAcl->rownerID);
+                ret = ConvertStrToUuid(stRowner, &acl->rownerID);
                 VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
                 OICFree(stRowner);
             }
@@ -699,10 +931,11 @@ exit:
     if (cborFindResult != CborNoError)
     {
         OIC_LOG(ERROR, TAG, "Failed to CBORPayloadToAcl");
-        DeleteACLList(headAcl);
-        headAcl = NULL;
+        DeleteACLList(acl);
+        acl = NULL;
     }
-    return headAcl;
+
+    return acl;
 }
 
 /**
@@ -720,8 +953,8 @@ static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
 {
     OIC_LOG(DEBUG, TAG, "IN RemoveACE");
 
-    OicSecAcl_t *acl = NULL;
-    OicSecAcl_t *tempAcl = NULL;
+    OicSecAce_t *ace = NULL;
+    OicSecAce_t *tempAce = NULL;
     bool deleteFlag = false;
     OCStackResult ret = OC_STACK_NO_RESOURCE;
 
@@ -734,12 +967,12 @@ static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
     //If resource is NULL then delete all the ACE for the subject.
     if (NULL == resource || resource[0] == '\0')
     {
-        LL_FOREACH_SAFE(gAcl, acl, tempAcl)
+        LL_FOREACH_SAFE(gAcl->aces, ace, tempAce)
         {
-            if (memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
+            if (memcmp(ace->subjectuuid.id, subject->id, sizeof(subject->id)) == 0)
             {
-                LL_DELETE(gAcl, acl);
-                FreeACE(acl);
+                LL_DELETE(gAcl->aces, ace);
+                FreeACE(ace);
                 deleteFlag = true;
             }
         }
@@ -750,42 +983,29 @@ static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
         //resource in the ACE for the subject then delete the whole ACE. If there are more resources
         //than the required resource in the ACE, for the subject then just delete the resource from
         //the resource array
-        LL_FOREACH_SAFE(gAcl, acl, tempAcl)
+        LL_FOREACH_SAFE(gAcl->aces, ace, tempAce)
         {
-            if (memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
+            if (memcmp(ace->subjectuuid.id, subject->id, sizeof(subject->id)) == 0)
             {
-                if (1 == acl->resourcesLen && strcmp(acl->resources[0], resource) == 0)
+                OicSecRsrc_t* rsrc = NULL;
+                OicSecRsrc_t* tempRsrc = NULL;
+                LL_FOREACH_SAFE(ace->resources, rsrc, tempRsrc)
                 {
-                    LL_DELETE(gAcl, acl);
-                    FreeACE(acl);
-                    deleteFlag = true;
-                    break;
-                }
-                else
-                {
-                    size_t resPos = -1;
-                    size_t i;
-                    for (i = 0; i < acl->resourcesLen; i++)
+                    if(strcmp(rsrc->href, resource) == 0)
                     {
-                        if (strcmp(acl->resources[i], resource) == 0)
-                        {
-                            resPos = i;
-                            break;
-                        }
-                    }
-                    if (0 <= (int) resPos)
-                    {
-                        OICFree(acl->resources[resPos]);
-                        acl->resources[resPos] = NULL;
-                        acl->resourcesLen -= 1;
-                        for (i = resPos; i < acl->resourcesLen; i++)
-                        {
-                            acl->resources[i] = acl->resources[i + 1];
-                        }
+                        LL_DELETE(ace->resources, rsrc);
+                        FreeRsrc(rsrc);
                         deleteFlag = true;
-                        break;
                     }
                 }
+
+                //If resource list is empty
+                if(NULL == ace->resources && true == deleteFlag)
+                {
+                    //Remove the ACE from ACL
+                    LL_DELETE(gAcl->aces, ace);
+                    FreeACE(ace);
+                }
             }
         }
     }
@@ -833,8 +1053,11 @@ static bool GetSubjectFromQueryString(const char *query, OicUuid_t *subject)
     {
         if (strncasecmp((char *) parseIter.attrPos, OIC_JSON_SUBJECTID_NAME, parseIter.attrLen) == 0)
         {
+            char strUuid[STRING_UUID_SIZE] = {0};
             VERIFY_SUCCESS(TAG, 0 != parseIter.valLen, ERROR);
-            memcpy(subject->id, parseIter.valPos, parseIter.valLen);
+            memcpy(strUuid, parseIter.valPos, parseIter.valLen);
+            OCStackResult res = ConvertStrToUuid(strUuid, subject);
+            VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
             return true;
         }
     }
@@ -882,20 +1105,24 @@ static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *e
     size_t size = 0;
     OCEntityHandlerResult ehRet;
 
-    // Process the REST querystring parameters
-    if (ehRequest->query)
+    OicUuid_t subject = {.id= { 0 } };
+
+    // In case, 'subject' field is included in REST request.
+    if (ehRequest->query && GetSubjectFromQueryString(ehRequest->query, &subject))
     {
+        OIC_LOG(DEBUG,TAG,"'subject' field is inculded in REST request.");
         OIC_LOG(DEBUG, TAG, "HandleACLGetRequest processing query");
 
-        OicUuid_t subject = {.id= { 0 } };
         char resource[MAX_URI_LENGTH] = { 0 };
 
-        OicSecAcl_t *savePtr = NULL;
-        const OicSecAcl_t *currentAce = NULL;
+        OicSecAce_t *savePtr = NULL;
+        const OicSecAce_t *currentAce = NULL;
+        OicSecAcl_t targetAcl;
 
-        // 'Subject' field is MUST for processing a querystring in REST request.
-        VERIFY_SUCCESS(TAG, true == GetSubjectFromQueryString(ehRequest->query, &subject), ERROR);
+        memcpy(&targetAcl.rownerID, &gAcl->rownerID, sizeof(OicUuid_t));
+        targetAcl.aces = NULL;
 
+        // 'Subject' field is MUST for processing a querystring in REST request.
         GetResourceFromQueryString(ehRequest->query, resource, sizeof(resource));
 
         /*
@@ -905,20 +1132,22 @@ static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *e
          */
         while ((currentAce = GetACLResourceData(&subject, &savePtr)))
         {
+            targetAcl.aces = (OicSecAce_t*)currentAce;
+
             /*
              * If REST querystring contains a specific resource, we need
              * to search for that resource in ACE.
              */
             if (resource[0] != '\0')
             {
-                for (size_t n = 0; n < currentAce->resourcesLen; n++)
+                OicSecRsrc_t *rsrc = NULL;
+                LL_FOREACH(currentAce->resources, rsrc)
                 {
-                    if ((currentAce->resources[n])
-                            && (0 == strcmp(resource, currentAce->resources[n])
-                                    || 0 == strcmp(WILDCARD_RESOURCE_URI, currentAce->resources[n])))
+                    if(0 == strcmp(rsrc->href, resource) ||
+                        0 == strcmp(WILDCARD_RESOURCE_URI, rsrc->href))
                     {
                         // Convert ACL data into CBOR format for transmission
-                        if (OC_STACK_OK != AclToCBORPayload(currentAce, &payload, &size))
+                        if (OC_STACK_OK != AclToCBORPayload(&targetAcl, &payload, &size))
                         {
                             ehRet = OC_EH_ERROR;
                         }
@@ -929,7 +1158,7 @@ static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *e
             else
             {
                 // Convert ACL data into CBOR format for transmission
-                if (OC_STACK_OK != AclToCBORPayload(currentAce, &payload, &size))
+                if (OC_STACK_OK != AclToCBORPayload(&targetAcl, &payload, &size))
                 {
                     ehRet = OC_EH_ERROR;
                 }
@@ -937,8 +1166,10 @@ static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *e
             }
         }
     }
+    // In case, 'subject' field is not included in REST request.
     else
     {
+        OIC_LOG(DEBUG,TAG,"'subject' field is not inculded in REST request.");
         // Convert ACL data into CBOR format for transmission.
         if (OC_STACK_OK != AclToCBORPayload(gAcl, &payload, &size))
         {
@@ -975,27 +1206,27 @@ static OCEntityHandlerResult HandleACLPostRequest(const OCEntityHandlerRequest *
         if (newAcl)
         {
             // Append the new ACL to existing ACL
-            LL_APPEND(gAcl, newAcl);
-            size_t size = 0;
-            // In case of unit test do not update persistant storage.
-            if (memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_ID, sizeof(newAcl->subject.id)) == 0
-                || memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_B64_ID, sizeof(newAcl->subject.id)) == 0)
+            OicSecAce_t* newAce = NULL;
+            OicSecAce_t* tempAce = NULL;
+            LL_FOREACH_SAFE(newAcl->aces, newAce, tempAce)
             {
-                ehRet = OC_EH_RESOURCE_CREATED;
+                LL_APPEND(gAcl->aces, newAce);
             }
-            else
+            newAcl->aces = NULL;
+
+            size_t size = 0;
+            uint8_t *cborPayload = NULL;
+            if (OC_STACK_OK == AclToCBORPayload(gAcl, &cborPayload, &size))
             {
-                uint8_t *cborPayload = NULL;
-                if (OC_STACK_OK == AclToCBORPayload(gAcl, &cborPayload, &size))
+                if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, cborPayload, size) == OC_STACK_OK)
                 {
-                    if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, cborPayload, size) == OC_STACK_OK)
-                    {
-                        ehRet = OC_EH_RESOURCE_CREATED;
-                    }
-                    OICFree(cborPayload);
+                    ehRet = OC_EH_RESOURCE_CREATED;
                 }
+                OICFree(cborPayload);
             }
         }
+
+        DeleteACLList(newAcl);
     }
 
     // Send payload to request originator
@@ -1087,7 +1318,7 @@ static OCStackResult CreateACLResource()
 
     ret = OCCreateResource(&gAclHandle,
                            OIC_RSRC_TYPE_SEC_ACL,
-                           OIC_MI_DEF,
+                           OC_RSRVD_INTERFACE_DEFAULT,
                            OIC_RSRC_ACL_URI,
                            ACLEntityHandler,
                            NULL,
@@ -1111,8 +1342,15 @@ OCStackResult SetDefaultACL(OicSecAcl_t *acl)
 OCStackResult GetDefaultACL(OicSecAcl_t** defaultAcl)
 {
     OCStackResult ret = OC_STACK_ERROR;
-
     OicUuid_t ownerId = { .id = { 0 } };
+    OicSecAcl_t *acl = NULL;
+    OicSecAce_t *ace = NULL;
+    OicSecRsrc_t* resRsrc = NULL;
+    OicSecRsrc_t* deviceRsrc = NULL;
+    OicSecRsrc_t* platformRsrc = NULL;
+    OicSecRsrc_t* aclRsrc = NULL;
+    OicSecRsrc_t* doxmRsrc = NULL;
+    OicSecRsrc_t* pstatRsrc = NULL;
 
     /*
      * TODO In future, when new virtual resources will be added in OIC
@@ -1121,48 +1359,133 @@ OCStackResult GetDefaultACL(OicSecAcl_t** defaultAcl)
      * mechanism in SVR database.
      */
 
-    const char *rsrcs[] = {
-        OC_RSRVD_WELL_KNOWN_URI,
-        OC_RSRVD_DEVICE_URI,
-        OC_RSRVD_PLATFORM_URI,
-        OC_RSRVD_RESOURCE_TYPES_URI,
-#ifdef WITH_PRESENCE
-        OC_RSRVD_PRESENCE_URI,
-#endif //WITH_PRESENCE
-        OIC_RSRC_ACL_URI,
-        OIC_RSRC_DOXM_URI,
-        OIC_RSRC_PSTAT_URI,
-    };
-
     if (!defaultAcl)
     {
         return OC_STACK_INVALID_PARAM;
     }
 
-    OicSecAcl_t *acl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    acl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
     VERIFY_NON_NULL(TAG, acl, ERROR);
 
-    // Subject -- Mandatory
-    memcpy(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(acl->subject));
-
-    // Resources -- Mandatory
-    acl->resourcesLen = sizeof(rsrcs) / sizeof(rsrcs[0]);
+    ace = (OicSecAce_t *) OICCalloc(1, sizeof(OicSecAce_t));
+    VERIFY_NON_NULL(TAG, ace, ERROR);
 
-    acl->resources = (char**) OICCalloc(acl->resourcesLen, sizeof(char*));
-    VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
+    LL_APPEND(acl->aces, ace);
 
-    for (size_t i = 0; i < acl->resourcesLen; i++)
-    {
-        size_t len = strlen(rsrcs[i]) + 1;
-        acl->resources[i] = (char*) OICMalloc(len * sizeof(char));
-        VERIFY_NON_NULL(TAG, (acl->resources[i]), ERROR);
-        OICStrcpy(acl->resources[i], len, rsrcs[i]);
-    }
+    // Subject -- Mandatory
+    memcpy(ace->subjectuuid.id, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t));
 
-    acl->permission = PERMISSION_READ;
-    acl->prdRecrLen = 0;
-    acl->periods = NULL;
-    acl->recurrences = NULL;
+    // Resources -- Mandatory
+    // /oic/res
+    resRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+    VERIFY_NON_NULL(TAG, resRsrc, ERROR);
+    LL_APPEND(ace->resources, resRsrc);
+    resRsrc->href = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
+    VERIFY_NON_NULL(TAG, (resRsrc->href), ERROR);
+    resRsrc->typeLen = 1;
+    resRsrc->types = (char**)OICCalloc(1, sizeof(char*));
+    VERIFY_NON_NULL(TAG, resRsrc->types, ERROR);
+    resRsrc->types[0] = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
+    VERIFY_NON_NULL(TAG, resRsrc->types[0], ERROR);
+    resRsrc->interfaceLen = 2;
+    resRsrc->interfaces = (char**)OICCalloc(resRsrc->interfaceLen, sizeof(char*));
+    VERIFY_NON_NULL(TAG, resRsrc->interfaces, ERROR);
+    resRsrc->interfaces[0] = OICStrdup(OC_RSRVD_INTERFACE_DEFAULT);
+    VERIFY_NON_NULL(TAG, resRsrc->interfaces[0], ERROR);
+    resRsrc->interfaces[1] = OICStrdup(OC_RSRVD_INTERFACE_READ);
+    VERIFY_NON_NULL(TAG, resRsrc->interfaces[1], ERROR);
+
+    // /oic/d
+    deviceRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+    VERIFY_NON_NULL(TAG, deviceRsrc, ERROR);
+    LL_APPEND(ace->resources, deviceRsrc);
+    deviceRsrc->href = OICStrdup(OC_RSRVD_DEVICE_URI);
+    VERIFY_NON_NULL(TAG, (deviceRsrc->href), ERROR);
+    deviceRsrc->typeLen = 1;
+    deviceRsrc->types = (char**)OICCalloc(1, sizeof(char*));
+    VERIFY_NON_NULL(TAG, deviceRsrc->types, ERROR);
+    deviceRsrc->types[0] = OICStrdup(OC_RSRVD_RESOURCE_TYPE_DEVICE);
+    VERIFY_NON_NULL(TAG, deviceRsrc->types[0], ERROR);
+    deviceRsrc->interfaceLen = 2;
+    deviceRsrc->interfaces = (char**)OICCalloc(deviceRsrc->interfaceLen, sizeof(char*));
+    VERIFY_NON_NULL(TAG, deviceRsrc->interfaces, ERROR);
+    deviceRsrc->interfaces[0] = OICStrdup(OC_RSRVD_INTERFACE_DEFAULT);
+    VERIFY_NON_NULL(TAG, deviceRsrc->interfaces[0], ERROR);
+    deviceRsrc->interfaces[1] = OICStrdup(OC_RSRVD_INTERFACE_READ);
+    VERIFY_NON_NULL(TAG, deviceRsrc->interfaces[1], ERROR);
+
+    // /oic/p
+    platformRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+    VERIFY_NON_NULL(TAG, platformRsrc, ERROR);
+    LL_APPEND(ace->resources, platformRsrc);
+    platformRsrc->href = OICStrdup(OC_RSRVD_PLATFORM_URI);
+    VERIFY_NON_NULL(TAG, (platformRsrc->href), ERROR);
+    platformRsrc->typeLen = 1;
+    platformRsrc->types = (char**)OICCalloc(1, sizeof(char*));
+    VERIFY_NON_NULL(TAG, platformRsrc->types, ERROR);
+    platformRsrc->types[0] = OICStrdup(OC_RSRVD_RESOURCE_TYPE_PLATFORM);
+    VERIFY_NON_NULL(TAG, platformRsrc->types[0], ERROR);
+    platformRsrc->interfaceLen = 2;
+    platformRsrc->interfaces = (char**)OICCalloc(platformRsrc->interfaceLen, sizeof(char*));
+    VERIFY_NON_NULL(TAG, platformRsrc->interfaces, ERROR);
+    platformRsrc->interfaces[0] = OICStrdup(OC_RSRVD_INTERFACE_DEFAULT);
+    VERIFY_NON_NULL(TAG, platformRsrc->interfaces[0], ERROR);
+    platformRsrc->interfaces[1] = OICStrdup(OC_RSRVD_INTERFACE_READ);
+    VERIFY_NON_NULL(TAG, platformRsrc->interfaces[1], ERROR);
+
+    // /oic/sec/acl
+    aclRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+    VERIFY_NON_NULL(TAG, aclRsrc, ERROR);
+    LL_APPEND(ace->resources, aclRsrc);
+    aclRsrc->href = OICStrdup(OIC_RSRC_ACL_URI);
+    VERIFY_NON_NULL(TAG, (aclRsrc->href), ERROR);
+    aclRsrc->typeLen = 1;
+    aclRsrc->types = (char**)OICCalloc(1, sizeof(char*));
+    VERIFY_NON_NULL(TAG, aclRsrc->types, ERROR);
+    aclRsrc->types[0] = OICStrdup(OIC_RSRC_TYPE_SEC_ACL);
+    VERIFY_NON_NULL(TAG, aclRsrc->types[0], ERROR);
+    aclRsrc->interfaceLen = 1;
+    aclRsrc->interfaces = (char**)OICCalloc(aclRsrc->interfaceLen, sizeof(char*));
+    VERIFY_NON_NULL(TAG, aclRsrc->interfaces, ERROR);
+    aclRsrc->interfaces[0] = OICStrdup(OC_RSRVD_INTERFACE_DEFAULT);
+    VERIFY_NON_NULL(TAG, aclRsrc->interfaces[0], ERROR);
+
+    // /oic/sec/doxm
+    doxmRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+    VERIFY_NON_NULL(TAG, doxmRsrc, ERROR);
+    LL_APPEND(ace->resources, doxmRsrc);
+    doxmRsrc->href = OICStrdup(OIC_RSRC_DOXM_URI);
+    VERIFY_NON_NULL(TAG, (doxmRsrc->href), ERROR);
+    doxmRsrc->typeLen = 1;
+    doxmRsrc->types = (char**)OICCalloc(1, sizeof(char*));
+    VERIFY_NON_NULL(TAG, doxmRsrc->types, ERROR);
+    doxmRsrc->types[0] = OICStrdup(OIC_RSRC_TYPE_SEC_DOXM);
+    VERIFY_NON_NULL(TAG, doxmRsrc->types[0], ERROR);
+    doxmRsrc->interfaceLen = 1;
+    doxmRsrc->interfaces = (char**)OICCalloc(doxmRsrc->interfaceLen, sizeof(char*));
+    VERIFY_NON_NULL(TAG, doxmRsrc->interfaces, ERROR);
+    doxmRsrc->interfaces[0] = OICStrdup(OC_RSRVD_INTERFACE_DEFAULT);
+    VERIFY_NON_NULL(TAG, doxmRsrc->interfaces[0], ERROR);
+
+    // /oic/sec/pstat
+    pstatRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+    VERIFY_NON_NULL(TAG, pstatRsrc, ERROR);
+    LL_APPEND(ace->resources, pstatRsrc);
+    pstatRsrc->href = OICStrdup(OIC_RSRC_PSTAT_URI);
+    VERIFY_NON_NULL(TAG, (pstatRsrc->href), ERROR);
+    pstatRsrc->typeLen = 1;
+    pstatRsrc->types = (char**)OICCalloc(1, sizeof(char*));
+    VERIFY_NON_NULL(TAG, pstatRsrc->types, ERROR);
+    pstatRsrc->types[0] = OICStrdup(OIC_RSRC_TYPE_SEC_PSTAT);
+    VERIFY_NON_NULL(TAG, pstatRsrc->types[0], ERROR);
+    pstatRsrc->interfaceLen = 1;
+    pstatRsrc->interfaces = (char**)OICCalloc(pstatRsrc->interfaceLen, sizeof(char*));
+    VERIFY_NON_NULL(TAG, pstatRsrc->interfaces, ERROR);
+    pstatRsrc->interfaces[0] = OICStrdup(OC_RSRVD_INTERFACE_DEFAULT);
+    VERIFY_NON_NULL(TAG, pstatRsrc->interfaces[0], ERROR);
+
+    ace->permission = PERMISSION_READ;
+    ace->validities = NULL;
 
     // Device ID is the owner of this default ACL
     if (GetDoxmResourceData() != NULL)
@@ -1178,8 +1501,6 @@ OCStackResult GetDefaultACL(OicSecAcl_t** defaultAcl)
 
     memcpy(&acl->rownerID, &ownerId, sizeof(OicUuid_t));
 
-    acl->next = NULL;
-
     *defaultAcl = acl;
     ret = OC_STACK_OK;
 
@@ -1202,7 +1523,7 @@ OCStackResult InitACLResource()
     size_t size = 0;
     ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_ACL_NAME, &data, &size);
     // If database read failed
-    if (ret != OC_STACK_OK)
+    if (OC_STACK_OK != ret)
     {
         OIC_LOG(DEBUG, TAG, "ReadSVDataFromPS failed");
     }
@@ -1218,7 +1539,11 @@ OCStackResult InitACLResource()
      */
     if (!gAcl)
     {
-        GetDefaultACL(&gAcl);
+        ret = GetDefaultACL(&gAcl);
+        if (OC_STACK_OK != ret)
+        {
+            OIC_LOG(ERROR, TAG, "Failed to create default ACL");
+        }
         // TODO Needs to update persistent storage
     }
     VERIFY_NON_NULL(TAG, gAcl, FATAL);
@@ -1247,10 +1572,10 @@ OCStackResult DeInitACLResource()
     return ret;
 }
 
-const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **savePtr)
+const OicSecAce_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAce_t **savePtr)
 {
-    OicSecAcl_t *acl = NULL;
-    OicSecAcl_t *begin = NULL;
+    OicSecAce_t *ace = NULL;
+    OicSecAce_t *begin = NULL;
 
     if (NULL == subjectId)
     {
@@ -1263,7 +1588,7 @@ const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **
      */
     if (NULL == *savePtr)
     {
-        begin = gAcl;
+        begin = gAcl->aces;
     }
     else
     {
@@ -1272,22 +1597,22 @@ const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **
          * savePtr and assign 'begin' to the next ACL after it in the linked
          * list and start searching from there.
          */
-        LL_FOREACH(gAcl, acl)
+        LL_FOREACH(gAcl->aces, ace)
         {
-            if (acl == *savePtr)
+            if (ace == *savePtr)
             {
-                begin = acl->next;
+                begin = ace->next;
             }
         }
     }
 
     // Find the next ACL corresponding to the 'subjectID' and return it.
-    LL_FOREACH(begin, acl)
+    LL_FOREACH(begin, ace)
     {
-        if (memcmp(&(acl->subject), subjectId, sizeof(OicUuid_t)) == 0)
+        if (memcmp(&(ace->subjectuuid), subjectId, sizeof(OicUuid_t)) == 0)
         {
-            *savePtr = acl;
-            return acl;
+            *savePtr = ace;
+            return ace;
         }
     }
 
@@ -1306,26 +1631,21 @@ OCStackResult InstallNewACL(const uint8_t *cborPayload, const size_t size)
     if (newAcl)
     {
         // Append the new ACL to existing ACL
-        LL_APPEND(gAcl, newAcl);
-
-        // Update persistent storage only if it is not WILDCARD_SUBJECT_ID
-        if (memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_ID, sizeof(newAcl->subject.id)) == 0
-            || memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_B64_ID, sizeof(newAcl->subject.id)) == 0)
+        OicSecAce_t* newAce = NULL;
+        LL_FOREACH(newAcl->aces, newAce)
         {
-            ret = OC_STACK_OK;
+            LL_APPEND(gAcl->aces, newAce);
         }
-        else
+
+        size_t size = 0;
+        uint8_t *payload = NULL;
+        if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
         {
-            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)
             {
-                if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size) == OC_STACK_OK)
-                {
-                    ret = OC_STACK_OK;
-                }
-                OICFree(payload);
+                ret = OC_STACK_OK;
             }
+            OICFree(payload);
         }
     }
 
@@ -1333,89 +1653,125 @@ OCStackResult InstallNewACL(const uint8_t *cborPayload, const size_t size)
 }
 
 /**
- * This function generates default ACL for security resource in case of owned status.
+ * This function generates default ACE for security resource in case of owned status.
  *
- * @return Default ACL for security resource.
+ * @return Default ACE for security resource.
  */
-static OicSecAcl_t* GetSecDefaultACL()
+static OicSecAce_t* GetSecDefaultACE()
 {
-    const char *sec_rsrcs[] = {
-        OIC_RSRC_DOXM_URI,
-        OIC_RSRC_PSTAT_URI
-    };
-    OicUuid_t ownerId = {.id = {0}};
-    OCStackResult res = OC_STACK_ERROR;
-    OicSecAcl_t* newDefaultAcl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
-    VERIFY_NON_NULL(TAG, newDefaultAcl, ERROR);
+    const int NUM_OF_DOXM_RT = 1;
+    const int NUM_OF_DOXM_IF  = 1;
+    const int NUM_OF_PSTAT_RT = 1;
+    const int NUM_OF_PSTAT_IF = 1;
+    const char *doxmRt[] = { OIC_RSRC_TYPE_SEC_DOXM };
+    const char *pstatRt[] = { OIC_RSRC_TYPE_SEC_PSTAT };
+    const char *doxmIf[] = { OC_RSRVD_INTERFACE_DEFAULT };
+    const char *pstatIf[] = { OC_RSRVD_INTERFACE_DEFAULT };
+    OicSecRsrc_t* doxmRsrc = NULL;
+    OicSecRsrc_t* pstatRsrc = NULL;
+
+    //Generate default ACE
+    OicSecAce_t* newAce = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+    VERIFY_NON_NULL(TAG, newAce, ERROR);
 
     // Subject -- Mandatory
-    memcpy(&(newDefaultAcl->subject), &WILDCARD_SUBJECT_ID, WILDCARD_SUBJECT_ID_LEN);
-
-    // Resources -- Mandatory
-    newDefaultAcl->resourcesLen = NUMBER_OF_DEFAULT_SEC_RSCS;
-    newDefaultAcl->resources = (char**)OICCalloc(NUMBER_OF_DEFAULT_SEC_RSCS, sizeof(char*));
-    VERIFY_NON_NULL(TAG, (newDefaultAcl->resources), ERROR);
+    memcpy(newAce->subjectuuid.id, &WILDCARD_SUBJECT_ID, WILDCARD_SUBJECT_ID_LEN);
+
+    //Resources -- Mandatory
+    //Add doxm
+    doxmRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+    VERIFY_NON_NULL(TAG, doxmRsrc, ERROR);
+    LL_APPEND(newAce->resources, doxmRsrc);
+    // pstat-href
+    doxmRsrc->href = OICStrdup(OIC_RSRC_DOXM_URI);
+    VERIFY_NON_NULL(TAG, (doxmRsrc->href), ERROR);
+    // pstat-rt
+    doxmRsrc->typeLen = NUM_OF_DOXM_RT;
+    doxmRsrc->types = (char**)OICCalloc(NUM_OF_DOXM_RT, sizeof(char*));
+    VERIFY_NON_NULL(TAG, (doxmRsrc->types), ERROR);
+    for(int i = 0; i < NUM_OF_DOXM_RT; i++)
+    {
+        doxmRsrc->types[i] = OICStrdup(doxmRt[i]);
+        VERIFY_NON_NULL(TAG, (doxmRsrc->types[i]), ERROR);
+    }
+    // pstat-if
+    doxmRsrc->interfaceLen = NUM_OF_DOXM_IF;
+    doxmRsrc->interfaces = (char**)OICCalloc(NUM_OF_DOXM_IF, sizeof(char*));
+    VERIFY_NON_NULL(TAG, (doxmRsrc->interfaces), ERROR);
+    for(int i = 0; i < NUM_OF_DOXM_IF; i++)
+    {
+        doxmRsrc->interfaces[i] = OICStrdup(doxmIf[i]);
+        VERIFY_NON_NULL(TAG, (doxmRsrc->interfaces[i]), ERROR);
+    }
 
-    for (size_t i = 0; i <  NUMBER_OF_DEFAULT_SEC_RSCS; i++)
+    //Add pstat
+    pstatRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+    VERIFY_NON_NULL(TAG, pstatRsrc, ERROR);
+    LL_APPEND(newAce->resources, pstatRsrc);
+    //pstat-href
+    pstatRsrc->href = OICStrdup(OIC_RSRC_PSTAT_URI);
+    VERIFY_NON_NULL(TAG, (pstatRsrc->href), ERROR);
+    //pstat-rt
+    pstatRsrc->typeLen = NUM_OF_PSTAT_RT;
+    pstatRsrc->types = (char**)OICCalloc(NUM_OF_PSTAT_RT, sizeof(char*));
+    VERIFY_NON_NULL(TAG, (pstatRsrc->types), ERROR);
+    for(int i = 0; i < NUM_OF_PSTAT_RT; i++)
     {
-        size_t len = strlen(sec_rsrcs[i]) + 1;
-        newDefaultAcl->resources[i] = (char*)OICMalloc(len * sizeof(char));
-        VERIFY_NON_NULL(TAG, (newDefaultAcl->resources[i]), ERROR);
-        OICStrcpy(newDefaultAcl->resources[i], len, sec_rsrcs[i]);
+        pstatRsrc->types[i] = OICStrdup(pstatRt[i]);
+        VERIFY_NON_NULL(TAG, (pstatRsrc->types[i]), ERROR);
+    }
+    // pstat-if
+    pstatRsrc->interfaceLen = NUM_OF_PSTAT_IF;
+    pstatRsrc->interfaces = (char**)OICCalloc(NUM_OF_PSTAT_IF, sizeof(char*));
+    VERIFY_NON_NULL(TAG, (pstatRsrc->interfaces), ERROR);
+    for(int i = 0; i < NUM_OF_PSTAT_IF; i++)
+    {
+        pstatRsrc->interfaces[i] = OICStrdup(pstatIf[i]);
+        VERIFY_NON_NULL(TAG, (pstatRsrc->interfaces[i]), ERROR);
     }
 
     // Permissions -- Mandatory
-    newDefaultAcl->permission = PERMISSION_READ;
+    newAce->permission = PERMISSION_READ;
 
     //Period -- Not Mandatory
-    newDefaultAcl->prdRecrLen = 0;
-    newDefaultAcl->periods = NULL;
-
-    //Recurrence -- Not Mandatory
-    newDefaultAcl->recurrences = NULL;
-
-    // Device ID is the owner of this default ACL
-    res = GetDoxmDeviceID(&ownerId);
-    VERIFY_SUCCESS(TAG, OC_STACK_OK == res, FATAL);
-
-    // Owners -- Mandatory
-    memcpy(&newDefaultAcl->rownerID, &ownerId, sizeof(OicUuid_t));
+    newAce->validities = NULL;
 
-    return newDefaultAcl;
+    return newAce;
 exit:
-    DeleteACLList(newDefaultAcl);
+    FreeACE(newAce);
     return NULL;
 
 }
 
-OCStackResult UpdateDefaultSecProvACL()
+OCStackResult UpdateDefaultSecProvACE()
 {
     OCStackResult ret = OC_STACK_OK;
-    OicSecAcl_t *acl = NULL;
-    OicSecAcl_t *tmp = NULL;
+    OicSecAce_t *ace = NULL;
+    OicSecAce_t *tempAce = NULL;
 
     if(gAcl)
     {
         int matchedRsrc = 0;
         bool isRemoved = false;
 
-        LL_FOREACH_SAFE(gAcl, acl, tmp)
+        LL_FOREACH_SAFE(gAcl->aces, ace, tempAce)
         {
             //Find default security resource ACL
-            if(memcmp(&acl->subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0 &&
-                ((PERMISSION_READ | PERMISSION_WRITE) == acl->permission))
+            if(memcmp(&ace->subjectuuid, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0 &&
+                ((PERMISSION_READ | PERMISSION_WRITE) == ace->permission))
             {
                 matchedRsrc = 0;
 
-                for(size_t i = 0; i < acl->resourcesLen; i++)
+                OicSecRsrc_t* rsrc = NULL;
+                LL_FOREACH(ace->resources, rsrc)
                 {
-                    if(strncmp(acl->resources[i], OIC_RSRC_DOXM_URI,
+                    if(strncmp(rsrc->href, OIC_RSRC_DOXM_URI,
                                strlen(OIC_RSRC_DOXM_URI) + 1) == 0 ||
-                       strncmp(acl->resources[i], OIC_RSRC_CRED_URI,
+                       strncmp(rsrc->href, OIC_RSRC_CRED_URI,
                                strlen(OIC_RSRC_CRED_URI) + 1) == 0 ||
-                       strncmp(acl->resources[i], OIC_RSRC_ACL_URI,
+                       strncmp(rsrc->href, OIC_RSRC_ACL_URI,
                                strlen(OIC_RSRC_ACL_URI) + 1) == 0 ||
-                       strncmp(acl->resources[i], OIC_RSRC_PSTAT_URI,
+                       strncmp(rsrc->href, OIC_RSRC_PSTAT_URI,
                                strlen(OIC_RSRC_PSTAT_URI) + 1) == 0)
                     {
                         matchedRsrc++;
@@ -1425,8 +1781,8 @@ OCStackResult UpdateDefaultSecProvACL()
                 //If default security resource ACL is detected, delete it.
                 if(NUMBER_OF_SEC_PROV_RSCS == matchedRsrc)
                 {
-                    LL_DELETE(gAcl, acl);
-                    FreeACE(acl);
+                    LL_DELETE(gAcl->aces, ace);
+                    FreeACE(ace);
                     isRemoved = true;
                 }
             }
@@ -1435,15 +1791,15 @@ OCStackResult UpdateDefaultSecProvACL()
         if(isRemoved)
         {
             /*
-             * Generate new security resource ACL as follows :
+             * Generate new security resource ACE as follows :
              *      subject : "*"
              *      resources :  '/oic/sec/doxm', '/oic/sec/pstat'
              *      permission : READ
              */
-            OicSecAcl_t *newDefaultAcl = GetSecDefaultACL();
-            if (newDefaultAcl)
+            OicSecAce_t *secDefaultAce = GetSecDefaultACE();
+            if (secDefaultAce)
             {
-                LL_APPEND(gAcl, newDefaultAcl);
+                LL_APPEND(gAcl->aces, secDefaultAce);
 
                 size_t size = 0;
                 uint8_t *payload = NULL;
index be21257..d29187f 100644 (file)
@@ -72,16 +72,6 @@ void DeleteAmaclList(OicSecAmacl_t* amacl)
     }
 }
 
-static size_t OicSecAmaclCount(const OicSecAmacl_t *secAmacl)
-{
-    size_t size = 0;
-    for (const OicSecAmacl_t *amacl = secAmacl; amacl; amacl = amacl->next)
-    {
-        size++;
-    }
-    return size;
-}
-
 OCStackResult AmaclToCBORPayload(const OicSecAmacl_t *amaclS, uint8_t **cborPayload,
                                  size_t *cborSize)
 {
@@ -269,7 +259,7 @@ OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t size,
     cborFindResult = cbor_value_enter_container(&amaclCbor, &amaclMap);
     VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Amacl Map.");
 
-    while(cbor_value_is_valid(&amaclMap))
+    while(cbor_value_is_valid(&amaclMap) && cbor_value_is_text_string(&amaclMap))
     {
         char *name = NULL;
         size_t len = 0;
@@ -288,7 +278,7 @@ OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t size,
             cborFindResult = cbor_value_enter_container(&amaclMap, &rsrcMap);
             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Resource Map");
 
-            while(cbor_value_is_valid(&rsrcMap))
+            while(cbor_value_is_valid(&rsrcMap) && cbor_value_is_text_string(&rsrcMap))
             {
                 // resource name
                 char *rsrcName = NULL;
@@ -323,7 +313,7 @@ OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t size,
                         cborFindResult = cbor_value_enter_container(&rsrcArray, &rMap);
                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Rlist Map");
 
-                        while(cbor_value_is_valid(&rMap))
+                        while(cbor_value_is_valid(&rMap) && cbor_value_is_text_string(&rMap))
                         {
                             char *rMapName = NULL;
                             size_t rMapNameLen = 0;
@@ -398,7 +388,7 @@ OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t size,
             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering AMS Array Container.");
             headAmacl->amss = (OicUuid_t *)OICCalloc(headAmacl->amssLen, sizeof(*headAmacl->amss));
             VERIFY_NON_NULL(TAG, headAmacl->amss, ERROR);
-            while (cbor_value_is_valid(&amsArray))
+            while (cbor_value_is_valid(&amsArray) && cbor_value_is_text_string(&amsArray))
             {
                 char *amssId = NULL;
                 cborFindResult = cbor_value_dup_text_string(&amsArray, &amssId, &len, NULL);
@@ -411,7 +401,7 @@ OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t size,
         }
 
         // Rowner -- Mandatory
-        if (0 == strcmp(OIC_JSON_ROWNERID_NAME, name))
+        if (0 == strcmp(OIC_JSON_ROWNERID_NAME, name) && cbor_value_is_text_string(&amaclMap))
         {
             char *stRowner = NULL;
             cborFindResult = cbor_value_dup_text_string(&amaclMap, &stRowner, &len, NULL);
@@ -551,7 +541,7 @@ static OCStackResult CreateAmaclResource()
 {
     OCStackResult ret = OCCreateResource(&gAmaclHandle,
                                          OIC_RSRC_TYPE_SEC_AMACL,
-                                         OIC_MI_DEF,
+                                         OC_RSRVD_INTERFACE_DEFAULT,
                                          OIC_RSRC_AMACL_URI,
                                          AmaclEntityHandler,
                                          NULL,
index 4ead7a3..c208d3f 100644 (file)
@@ -56,7 +56,7 @@ OCStackResult DiscoverAmsService(PEContext_t *context)
 
     OCStackResult ret = OC_STACK_ERROR;
     const char DOXM_DEVICEID_QUERY_FMT[] = "%s?%s=%s";
-    char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
+    char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     OCCallbackData cbData = {.context=NULL};
 
     VERIFY_NON_NULL(TAG, context, ERROR);
@@ -120,7 +120,7 @@ static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle ha
         return OC_STACK_KEEP_TRANSACTION;
     }
 
-    OicUuid_t deviceId = {.id={}};
+    OicUuid_t deviceId = {.id={0}};
     memcpy(&deviceId, &doxm->deviceID, sizeof(deviceId));
     OICFree(doxm);
 
@@ -151,7 +151,7 @@ OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,OCDevAddr *dev
 
     const char RES_DOXM_QUERY_FMT[] = "%s?%s=%s";
     OCCallbackData cbData = {.context=NULL};
-    char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
+    char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     snprintf(uri, sizeof(uri), RES_DOXM_QUERY_FMT, OC_RSRVD_WELL_KNOWN_URI,
             OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DOXM);
 
@@ -226,12 +226,9 @@ OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivit
 {
     OCStackResult ret = OC_STACK_ERROR;
     const char GET_ACE_QUERY_FMT[] = "%s?%s=%s;%s=%s";
-    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
-    uint32_t outLen = 0;
-    char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
+    char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     OCCallbackData cbData = {.context=NULL};
     OCDevAddr destAddr = {.adapter = OC_ADAPTER_IP};
-    B64Result b64Ret;
     char *subID = NULL;
 
     VERIFY_NON_NULL(TAG, context, ERROR);
@@ -400,7 +397,7 @@ bool FoundAmaclForRequest(PEContext_t *context)
 
 void ProcessAMSRequest(PEContext_t *context)
 {
-    OicUuid_t  emptyUuid = {.id={}};
+    OicUuid_t  emptyUuid = {.id={0}};
     OIC_LOG_V(INFO, TAG, "Entering %s", __func__);
     if (NULL != context)
     {
index 07bc8ea..7bac5e1 100644 (file)
 #define __STDC_LIMIT_MACROS
 
 #include <stdlib.h>
-#ifdef WITH_ARDUINO
+#ifdef HAVE_STRING_H
 #include <string.h>
-#else
+#endif
+#ifdef HAVE_STRINGS_H
 #include <strings.h>
 #endif
 #include <stdint.h>
@@ -124,7 +125,7 @@ static size_t OicSecCredCount(const OicSecCred_t *secCred)
 }
 
 OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload,
-                                size_t *cborSize)
+                                size_t *cborSize, int secureFlag)
 {
     if (NULL == credS || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
     {
@@ -180,7 +181,7 @@ OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload
             mapSize++;
         }
 #endif /* __WITH_X509__ */
-        if (cred->privateData.data)
+        if (!secureFlag && cred->privateData.data)
         {
             mapSize++;
         }
@@ -245,7 +246,7 @@ OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload
         }
 #endif /*__WITH_X509__*/
         //PrivateData -- Not Mandatory
-        if(cred->privateData.data)
+        if(!secureFlag && cred->privateData.data)
         {
             CborEncoder privateMap;
             const size_t privateMapSize = 2;
@@ -257,20 +258,45 @@ OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload
             cborEncoderResult = cbor_encoder_create_map(&credMap, &privateMap, privateMapSize);
             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PrivateData Map");
 
-            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.");
-
             // TODO: Need to data strucure modification for OicSecKey_t.
-            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_RAW,
-                strlen(OIC_SEC_ENCODING_RAW));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Encoding Value.");
+            // TODO: Added as workaround, will be replaced soon.
+            if(OIC_ENCODING_RAW == 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_RAW,
+                    strlen(OIC_SEC_ENCODING_RAW));
+                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 if(OIC_ENCODING_BASE64 == 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_BASE64,
+                    strlen(OIC_SEC_ENCODING_BASE64));
+                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_text_string(&privateMap, (char*)(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.");
+                VERIFY_CBOR_SUCCESS(TAG, CborErrorUnknownType, "Failed Adding Private Encoding Value.");
+            }
 
             cborEncoderResult = cbor_encoder_close_container(&credMap, &privateMap);
             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing PrivateData Map.");
@@ -332,7 +358,7 @@ exit:
         // Since the allocated initial memory failed, double the memory.
         cborLen += encoder.ptr - encoder.end;
         cborEncoderResult = CborNoError;
-        ret = CredToCBORPayload(credS, cborPayload, &cborLen);
+        ret = CredToCBORPayload(credS, cborPayload, &cborLen, secureFlag);
         *cborSize = cborLen;
     }
 
@@ -375,7 +401,7 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
         char* tagName = NULL;
         size_t len = 0;
         CborType type = cbor_value_get_type(&CredRootMap);
-        if (type == CborTextStringType)
+        if (type == CborTextStringType && cbor_value_is_text_string(&CredRootMap))
         {
             cborFindResult = cbor_value_dup_text_string(&CredRootMap, &tagName, &len, NULL);
             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in CRED Root Map.");
@@ -419,7 +445,7 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
 
                     VERIFY_NON_NULL(TAG, cred, ERROR);
 
-                    while(cbor_value_is_valid(&credMap))
+                    while(cbor_value_is_valid(&credMap) && cbor_value_is_text_string(&credMap))
                     {
                         char* name = NULL;
                         CborType type = cbor_value_get_type(&credMap);
@@ -435,8 +461,10 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                             //credid
                             if (strcmp(name, OIC_JSON_CREDID_NAME)  == 0)
                             {
-                                cborFindResult = cbor_value_get_uint64(&credMap, (uint64_t *) &cred->credId);
+                                uint64_t credId = 0;
+                                cborFindResult = cbor_value_get_uint64(&credMap, &credId);
                                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CredId.");
+                                cred->credId = (uint16_t)credId;
                             }
                             // subjectid
                             if (strcmp(name, OIC_JSON_SUBJECTID_NAME)  == 0)
@@ -451,8 +479,10 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                             // credtype
                             if (strcmp(name, OIC_JSON_CREDTYPE_NAME)  == 0)
                             {
-                                cborFindResult = cbor_value_get_uint64(&credMap, (uint64_t *) &cred->credType);
+                                uint64_t credType = 0;
+                                cborFindResult = cbor_value_get_uint64(&credMap, &credType);
                                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CredType.");
+                                cred->credType = (OicSecCredType_t)credType;
                             }
                             // privatedata
                             if (strcmp(name, OIC_JSON_PRIVATEDATA_NAME)  == 0)
@@ -464,7 +494,7 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                                 {
                                     char* privname = NULL;
                                     CborType type = cbor_value_get_type(&privateMap);
-                                    if (type == CborTextStringType)
+                                    if (type == CborTextStringType && cbor_value_is_text_string(&privateMap))
                                     {
                                         cborFindResult = cbor_value_dup_text_string(&privateMap, &privname,
                                                 &len, NULL);
@@ -477,14 +507,48 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                                         // PrivateData::privdata -- Mandatory
                                         if (strcmp(privname, OIC_JSON_DATA_NAME) == 0)
                                         {
-                                            cborFindResult = cbor_value_dup_byte_string(&privateMap, &cred->privateData.data,
-                                                &cred->privateData.len, NULL);
+                                            if(cbor_value_is_byte_string(&privateMap))
+                                            {
+                                                cborFindResult = cbor_value_dup_byte_string(&privateMap, &cred->privateData.data,
+                                                    &cred->privateData.len, NULL);
+                                            }
+                                            else if(cbor_value_is_text_string(&privateMap))
+                                            {
+                                                cborFindResult = cbor_value_dup_text_string(&privateMap, (char**)(&cred->privateData.data),
+                                                    &cred->privateData.len, NULL);
+                                            }
+                                            else
+                                            {
+                                                cborFindResult = CborErrorUnknownType;
+                                                OIC_LOG(ERROR, TAG, "Unknow type for private data.");
+                                            }
                                             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PrivateData.");
                                         }
+
                                         // PrivateData::encoding -- Mandatory
                                         if (strcmp(privname, OIC_JSON_ENCODING_NAME) == 0)
                                         {
-                                            // TODO: Need to update data structure, just ignore encoding value now.
+                                            // TODO: Added as workaround. Will be replaced soon.
+                                            char* strEncoding = NULL;
+                                            cborFindResult = cbor_value_dup_text_string(&privateMap, &strEncoding, &len, NULL);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding EncodingType");
+
+                                            if(strcmp(strEncoding, OIC_SEC_ENCODING_RAW) == 0)
+                                            {
+                                                cred->privateData.encoding = OIC_ENCODING_RAW;
+                                            }
+                                            else if(strcmp(strEncoding, OIC_SEC_ENCODING_BASE64) == 0)
+                                            {
+                                                cred->privateData.encoding = OIC_ENCODING_BASE64;
+                                            }
+                                            else
+                                            {
+                                                //For unit test
+                                                cred->privateData.encoding = OIC_ENCODING_RAW;
+                                                OIC_LOG(WARNING, TAG, "Unknow encoding type dectected for private data.");
+                                            }
+
+                                            OICFree(strEncoding);
                                         }
                                     }
                                     if (cbor_value_is_valid(&privateMap))
@@ -506,7 +570,7 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                                 {
                                     char* pubname = NULL;
                                     CborType type = cbor_value_get_type(&pubMap);
-                                    if (type == CborTextStringType)
+                                    if (type == CborTextStringType && cbor_value_is_text_string(&pubMap))
                                     {
                                         cborFindResult = cbor_value_dup_text_string(&pubMap, &pubname,
                                                 &len, NULL);
@@ -517,7 +581,7 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                                     if (pubname)
                                     {
                                         // PrivateData::privdata -- Mandatory
-                                        if (strcmp(pubname, OIC_JSON_DATA_NAME) == 0)
+                                        if (strcmp(pubname, OIC_JSON_DATA_NAME) == 0 && cbor_value_is_byte_string(&pubMap))
                                         {
                                             cborFindResult = cbor_value_dup_byte_string(&pubMap, &cred->publicData.data,
                                                 &cred->publicData.len, NULL);
@@ -563,7 +627,7 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
             }
 
             //ROwner -- Mandatory
-            if (strcmp(tagName, OIC_JSON_ROWNERID_NAME)  == 0)
+            if (strcmp(tagName, OIC_JSON_ROWNERID_NAME)  == 0 && cbor_value_is_text_string(&CredRootMap))
             {
                 char *stRowner = NULL;
                 cborFindResult = cbor_value_dup_text_string(&CredRootMap, &stRowner, &len, NULL);
@@ -634,6 +698,28 @@ OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t cr
         VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
         memcpy(cred->privateData.data, privateData->data, privateData->len);
         cred->privateData.len = privateData->len;
+
+        // TODO: Added as workaround. Will be replaced soon.
+        cred->privateData.encoding = OIC_ENCODING_RAW;
+
+#if 0
+        // NOTE: Test codes to use base64 for credential.
+        uint32_t outSize = 0;
+        size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((privateData->len + 1));
+        char* b64Buf = (uint8_t *)OICCalloc(1, b64BufSize);
+        VERIFY_NON_NULL(TAG, b64Buf, ERROR);
+        b64Encode(privateData->data, privateData->len, b64Buf, b64BufSize, &outSize);
+
+        OICFree( cred->privateData.data );
+        cred->privateData.data = (uint8_t *)OICCalloc(1, outSize + 1);
+        VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
+
+        strcpy(cred->privateData.data, b64Buf);
+        cred->privateData.encoding = OIC_ENCODING_BASE64;
+        cred->privateData.len = outSize;
+        OICFree(b64Buf);
+#endif //End of Test codes
+
     }
 
     VERIFY_NON_NULL(TAG, rownerID, ERROR);
@@ -658,7 +744,8 @@ static bool UpdatePersistentStorage(const OicSecCred_t *cred)
     {
         uint8_t *payload = NULL;
         size_t size = 0;
-        OCStackResult res = CredToCBORPayload(cred, &payload, &size);
+        int secureFlag = 0;
+        OCStackResult res = CredToCBORPayload(cred, &payload, &size, secureFlag);
         if ((OC_STACK_OK == res) && payload)
         {
             if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, payload, size))
@@ -847,10 +934,35 @@ static bool FillPrivateDataOfOwnerPSK(OicSecCred_t* receviedCred, const CAEndpoi
     OIC_LOG_BUFFER(DEBUG, TAG, ownerPSK, OWNER_PSK_LENGTH_128);
 
     //Generate owner credential based on recevied credential information
-    receviedCred->privateData.data = (uint8_t *)OICCalloc(1, OWNER_PSK_LENGTH_128);
-    VERIFY_NON_NULL(TAG, receviedCred->privateData.data, ERROR);
-    receviedCred->privateData.len = OWNER_PSK_LENGTH_128;
-    memcpy(receviedCred->privateData.data, ownerPSK, OWNER_PSK_LENGTH_128);
+
+    // TODO: Added as workaround, will be replaced soon.
+    if(OIC_ENCODING_RAW == receviedCred->privateData.encoding)
+    {
+        receviedCred->privateData.data = (uint8_t *)OICCalloc(1, OWNER_PSK_LENGTH_128);
+        VERIFY_NON_NULL(TAG, receviedCred->privateData.data, ERROR);
+        receviedCred->privateData.len = OWNER_PSK_LENGTH_128;
+        memcpy(receviedCred->privateData.data, ownerPSK, OWNER_PSK_LENGTH_128);
+    }
+    else if(OIC_ENCODING_BASE64 == receviedCred->privateData.encoding)
+    {
+        uint32_t b64OutSize = 0;
+        size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((OWNER_PSK_LENGTH_128 + 1));
+        char* b64Buf = OICCalloc(1, b64BufSize);
+        VERIFY_NON_NULL(TAG, b64Buf, ERROR);
+
+        b64Encode(ownerPSK, OWNER_PSK_LENGTH_128, b64Buf, b64BufSize, &b64OutSize);
+
+        receviedCred->privateData.data = (uint8_t *)OICCalloc(1, b64OutSize + 1);
+        VERIFY_NON_NULL(TAG, receviedCred->privateData.data, ERROR);
+        receviedCred->privateData.len = b64OutSize;
+        strncpy((char*)receviedCred->privateData.data, b64Buf, b64OutSize);
+        receviedCred->privateData.data[b64OutSize] = '\0';
+    }
+    else
+    {
+        // TODO: error
+        VERIFY_SUCCESS(TAG, OIC_ENCODING_UNKNOW, ERROR);
+    }
 
     OIC_LOG(INFO, TAG, "PrivateData of OwnerPSK was calculated successfully");
 
@@ -864,22 +976,23 @@ exit:
 
 #endif //__WITH_DTLS__
 
-static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
 {
     OCEntityHandlerResult ret = OC_EH_ERROR;
-    OIC_LOG(DEBUG, TAG, "HandleCREDPutRequest IN");
+    OIC_LOG(DEBUG, TAG, "HandleCREDPostRequest IN");
 
     //Get binary representation of cbor
     OicSecCred_t *cred  = NULL;
     uint8_t *payload = (((OCSecurityPayload*)ehRequest->payload)->securityData);
     size_t size = (((OCSecurityPayload*)ehRequest->payload)->payloadSize);
+
     OCStackResult res = CBORPayloadToCred(payload, size, &cred);
     if (res == OC_STACK_OK)
     {
 #ifdef __WITH_DTLS__
         OicUuid_t emptyUuid = {.id={0}};
         const OicSecDoxm_t* doxm = GetDoxmResourceData();
-        if(false == doxm->owned && memcmp(&(doxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0)
+        if(doxm && false == doxm->owned && memcmp(&(doxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0)
         {
             //in case of owner PSK
             switch(cred->credType)
@@ -1008,29 +1121,36 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR
         }
         FreeCred(cred);
     }
-    OIC_LOG(DEBUG, TAG, "HandleCREDPutRequest OUT");
+    OIC_LOG(DEBUG, TAG, "HandleCREDPostRequest OUT");
     return ret;
 }
 
-static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
+/**
+ * The entity handler determines how to process a GET request.
+ */
+static OCEntityHandlerResult HandleGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
-    OCEntityHandlerResult ret = OC_EH_ERROR;
+    OIC_LOG(INFO, TAG, "HandleGetRequest  processing GET request");
 
-    //Get binary representation of CBOR
-    OicSecCred_t *cred  = NULL;
-    uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData;
-    size_t size = ((OCSecurityPayload*)ehRequest->payload)->payloadSize;
-    OCStackResult res = CBORPayloadToCred(payload, size, &cred);
-    if ((OC_STACK_OK == res) && cred)
+    // Convert Cred data into CBOR for transmission
+    size_t size = 0;
+    uint8_t *payload = NULL;
+    int secureFlag = 1;
+
+    const OicSecCred_t *cred = gCred;
+    OCStackResult res = CredToCBORPayload(cred, &payload, &size, secureFlag);
+
+    // A device should always have a default cred. Therefore, payload should never be NULL.
+    OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
+
+    // Send response payload to request originator
+    if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, payload, size))
     {
-        //If the Post request credential has credId, it will be
-        //discarded and the next available credId will be assigned
-        //to it before getting appended to the existing credential
-        //list and updating svr database.
-        ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
+        ehRet = OC_EH_ERROR;
+        OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandlePstatGetRequest");
     }
-
-    return ret;
+    OICFree(payload);
+    return ehRet;
 }
 
 static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *ehRequest)
@@ -1082,15 +1202,13 @@ OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
     if (flag & OC_REQUEST_FLAG)
     {
         OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
-        //TODO :  Handle PUT/DEL methods
+        //TODO :  Remove Handle PUT methods once CTT have changed to POST on OTM
         switch (ehRequest->method)
         {
             case OC_REST_GET:
-                ret = OC_EH_FORBIDDEN;
+                ret = HandleGetRequest(ehRequest);;
                 break;
             case OC_REST_PUT:
-                ret = HandlePutRequest(ehRequest);
-                break;
             case OC_REST_POST:
                 ret = HandlePostRequest(ehRequest);
                 break;
@@ -1114,11 +1232,11 @@ OCStackResult CreateCredResource()
 {
     OCStackResult ret = OCCreateResource(&gCredHandle,
                                          OIC_RSRC_TYPE_SEC_CRED,
-                                         OIC_MI_DEF,
+                                         OC_RSRVD_INTERFACE_DEFAULT,
                                          OIC_RSRC_CRED_URI,
                                          CredEntityHandler,
                                          NULL,
-                                         OC_RES_PROP_NONE);
+                                         OC_SECURE);
 
     if (OC_STACK_OK != ret)
     {
@@ -1207,7 +1325,7 @@ int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type,
         case CA_DTLS_PSK_HINT:
         case CA_DTLS_PSK_IDENTITY:
             {
-                OicUuid_t deviceID = {.id={}};
+                OicUuid_t deviceID = {.id={0}};
                 // Retrieve Device ID from doxm resource
                 if ( OC_STACK_OK != GetDoxmDeviceID(&deviceID) )
                 {
@@ -1247,15 +1365,42 @@ int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type,
                             if(IOTVTICAL_VALID_ACCESS != IsRequestWithinValidTime(cred->period, NULL))
                             {
                                 OIC_LOG (INFO, TAG, "Credentials are expired.");
-                                ret = -1;
                                 return ret;
                             }
                         }
 
                         // Copy PSK.
-                        result_length = cred->privateData.len;
-                        memcpy(result, cred->privateData.data, result_length);
-                        return result_length;
+                        // TODO: Added as workaround. Will be replaced soon.
+                        if(OIC_ENCODING_RAW == cred->privateData.encoding)
+                        {
+                            ret = cred->privateData.len;
+                            memcpy(result, cred->privateData.data, ret);
+                        }
+                        else if(OIC_ENCODING_BASE64 == cred->privateData.encoding)
+                        {
+                            size_t outBufSize = B64DECODE_OUT_SAFESIZE((cred->privateData.len + 1));
+                            uint8_t* outKey = OICCalloc(1, outBufSize);
+                            uint32_t outKeySize;
+                            if(NULL == outKey)
+                            {
+                                OIC_LOG (ERROR, TAG, "Failed to memoray allocation.");
+                                return ret;
+                            }
+
+                            if(B64_OK == b64Decode((char*)cred->privateData.data, cred->privateData.len, outKey, outBufSize, &outKeySize))
+                            {
+                                memcpy(result, outKey, outKeySize);
+                                ret = outKeySize;
+                            }
+                            else
+                            {
+                                OIC_LOG (ERROR, TAG, "Failed to base64 decoding.");
+                            }
+
+                            OICFree(outKey);
+                        }
+
+                        return ret;
                     }
                 }
             }
@@ -1264,7 +1409,6 @@ int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type,
         default:
             {
                 OIC_LOG (ERROR, TAG, "Wrong value passed for CADtlsPskCredType_t.");
-                ret = -1;
             }
             break;
     }
@@ -1297,7 +1441,7 @@ OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t cre
     }
 
     uint8_t privData[OWNER_PSK_LENGTH_128] = {0,};
-    OicSecKey_t privKey = {privData, OWNER_PSK_LENGTH_128};
+    OicSecKey_t privKey = {privData, OWNER_PSK_LENGTH_128, OIC_ENCODING_RAW};
     OicSecCred_t* cred = NULL;
     int dtlsRes = DeriveCryptoKeyFromPassword((const unsigned char *)pin, pinSize, rownerID->id,
                                               UUID_LENGTH, PBKDF_ITERATIONS,
@@ -1408,6 +1552,7 @@ OCStackResult SetCredRownerId(const OicUuid_t* newROwner)
     OCStackResult ret = OC_STACK_ERROR;
     uint8_t *cborPayload = NULL;
     size_t size = 0;
+    int secureFlag = 0;
     OicUuid_t prevId = {.id={0}};
 
     if(NULL == newROwner)
@@ -1424,7 +1569,7 @@ OCStackResult SetCredRownerId(const OicUuid_t* newROwner)
         memcpy(prevId.id, gCred->rownerID.id, sizeof(prevId.id));
         memcpy(gCred->rownerID.id, newROwner->id, sizeof(newROwner->id));
 
-        ret = CredToCBORPayload(gCred, &cborPayload, &size);
+        ret = CredToCBORPayload(gCred, &cborPayload, &size, secureFlag);
         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
 
         ret = UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, cborPayload, size);
index 53f2ca2..23781b7 100644 (file)
@@ -373,7 +373,7 @@ static OCStackResult CreateCRLResource()
 {
     OCStackResult ret = OCCreateResource(&gCrlHandle,
                                          OIC_RSRC_TYPE_SEC_CRL,
-                                         OIC_MI_DEF,
+                                         OC_RSRVD_INTERFACE_DEFAULT,
                                          OIC_RSRC_CRL_URI,
                                          CRLEntityHandler,
                                          NULL,
@@ -468,12 +468,13 @@ OCStackResult InitCRLResource()
 /**
  * Perform cleanup for ACL resources.
  */
-void DeInitCRLResource()
+OCStackResult DeInitCRLResource()
 {
-    OCDeleteResource(gCrlHandle);
+    OCStackResult result = OCDeleteResource(gCrlHandle);
     gCrlHandle = NULL;
     DeleteCrlBinData(gCrl);
     gCrl = NULL;
+    return result;
 }
 
 OicSecCrl_t *GetCRLResource()
@@ -516,17 +517,22 @@ uint8_t *GetCrl()
     return NULL;
 }
 
-void  GetDerCrl(ByteArray crlArray)
+void  GetDerCrl(ByteArray* crlArray)
 {
+    if(NULL == crlArray)
+    {
+        return;
+    }
     OicSecCrl_t * crlRes = GetCRLResource();
-    if (crlRes && crlRes->CrlData.len <= crlArray.len)
+    if (NULL != crlArray->data && NULL != crlRes
+        && NULL !=crlRes->CrlData.data && crlRes->CrlData.len <= crlArray->len)
     {
-        memcpy(crlArray.data, crlRes->CrlData.data, crlRes->CrlData.len);
-        crlArray.len = crlRes->CrlData.len;
+        memcpy(crlArray->data, crlRes->CrlData.data, crlRes->CrlData.len);
+        crlArray->len = crlRes->CrlData.len;
     }
     else
     {
-        crlArray.len = 0;
+        crlArray->len = 0;
     }
     DeleteCrlBinData(crlRes);
 }
index 5606598..9670e67 100644 (file)
 #ifndef _POSIX_C_SOURCE\r
 #define _POSIX_C_SOURCE 200112L\r
 #endif\r
-#ifndef WITH_ARDUINO\r
+#ifdef HAVE_UNISTD_H\r
 #include <unistd.h>\r
+#endif\r
+#ifdef HAVE_TIME_H\r
 #include <time.h>\r
+#endif\r
+#ifdef HAVE_SYS_TIME_H\r
 #include <sys/time.h>\r
 #endif\r
+#ifdef HAVE_STRING_H\r
 #include <string.h>\r
+#endif\r
 \r
 #include "ocstack.h"\r
 #include "oic_malloc.h"\r
@@ -65,6 +71,7 @@ typedef struct DPairData
     OCDirectPairingDev_t        *peer;                         /**< Pointer to pairing target info.**/\r
     char                                  pin[DP_PIN_LENGTH];  /**< PIN **/\r
     OCDirectPairingResultCB    resultCallback;           /**< Pointer to result callback.**/\r
+    void *userCtx;                                      /** < user context to pass in callback **/\r
 } DPairData_t;\r
 \r
 static OCDirectPairingDev_t *g_dp_paired = NULL;\r
@@ -347,7 +354,7 @@ static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHand
             if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))\r
             {\r
                 OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");\r
-                resultCallback(peer, OC_STACK_ERROR);\r
+                resultCallback(dpairData->userCtx, peer, OC_STACK_ERROR);\r
                 return OC_STACK_DELETE_TRANSACTION;\r
             }\r
 \r
@@ -356,7 +363,7 @@ static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHand
             if(OC_STACK_OK != res)\r
             {\r
                 OIC_LOG(ERROR, TAG, "Failed to PairingPSK generation");\r
-                resultCallback(peer, res);\r
+                resultCallback(dpairData->userCtx, peer, res);\r
                 return OC_STACK_DELETE_TRANSACTION;\r
             }\r
 \r
@@ -385,7 +392,7 @@ static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHand
                 OIC_LOG(ERROR, TAG, "Error while adding a device to paired list.");\r
             }\r
 \r
-            resultCallback(peer, OC_STACK_OK);\r
+            resultCallback(dpairData->userCtx, peer, OC_STACK_OK);\r
 \r
             return OC_STACK_DELETE_TRANSACTION;\r
         }\r
@@ -399,7 +406,7 @@ static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHand
         OIC_LOG(ERROR, TAG, "DirectPairingFinalizeHandler received Null clientResponse");\r
     }\r
 \r
-    resultCallback(peer, OC_STACK_ERROR);\r
+    resultCallback(dpairData->userCtx, peer, OC_STACK_ERROR);\r
     OICFree(dpairData);\r
     return OC_STACK_DELETE_TRANSACTION;\r
 }\r
@@ -412,7 +419,7 @@ static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHand
  *\r
  * @return OC_STACK_OK on success otherwise error.\r
  */\r
-OCStackResult FinalizeDirectPairing(OCDirectPairingDev_t* peer,\r
+OCStackResult FinalizeDirectPairing(void *ctx, OCDirectPairingDev_t* peer,\r
                                                      OCDirectPairingResultCB resultCallback)\r
 {\r
     if(NULL == peer)\r
@@ -474,6 +481,7 @@ OCStackResult FinalizeDirectPairing(OCDirectPairingDev_t* peer,
     }\r
     dpairData->peer = peer;\r
     dpairData->resultCallback = resultCallback;\r
+    dpairData->userCtx = ctx;\r
 \r
     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};\r
     cbData.cb = DirectPairingFinalizeHandler;\r
@@ -525,17 +533,17 @@ void DirectPairingDTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInf
             {\r
                 OIC_LOG(INFO, TAG, "Now, finalize Direct-Pairing procedure.");\r
 \r
-                res = FinalizeDirectPairing(peer, resultCallback);\r
+                res = FinalizeDirectPairing(g_dp_proceed_ctx->userCtx, peer, resultCallback);\r
                 if(OC_STACK_OK != res)\r
                 {\r
                     OIC_LOG(ERROR, TAG, "Failed to finalize direct-pairing");\r
-                    resultCallback(peer, res);\r
+                    resultCallback(g_dp_proceed_ctx->userCtx, peer, res);\r
                 }\r
             }\r
             else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)\r
             {\r
                 OIC_LOG(INFO, TAG, "DirectPairingDTLSHandshakeCB - Authentication failed");\r
-                resultCallback(peer, OC_STACK_AUTHENTICATION_FAILURE);\r
+                resultCallback(g_dp_proceed_ctx->userCtx, peer, OC_STACK_AUTHENTICATION_FAILURE);\r
             }\r
 \r
 #ifdef __WITH_DTLS__\r
@@ -653,7 +661,7 @@ exit:
             g_dp_proceed_ctx = NULL;\r
         }\r
 \r
-        resultCallback(dpairData->peer, res);\r
+        resultCallback(dpairData->userCtx, dpairData->peer, res);\r
     }\r
     OIC_LOG_V(INFO, TAG, "OUT DirectPairingHandler.");\r
     return OC_STACK_DELETE_TRANSACTION;\r
@@ -668,8 +676,8 @@ exit:
  *\r
  * @return OC_STACK_OK on success otherwise error.\r
  */\r
-OCStackResult DPDirectPairing(OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, char *pinNumber,\r
-                                                     OCDirectPairingResultCB resultCallback)\r
+OCStackResult DPDirectPairing(void *ctx, OCDirectPairingDev_t* peer, OicSecPrm_t pmSel,\r
+                                char *pinNumber, OCDirectPairingResultCB resultCallback)\r
 {\r
     if(NULL == peer || NULL == pinNumber)\r
     {\r
@@ -732,6 +740,7 @@ OCStackResult DPDirectPairing(OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, cha
     dpairData->peer = peer;\r
     memcpy(dpairData->pin, pinNumber, DP_PIN_LENGTH);\r
     dpairData->resultCallback = resultCallback;\r
+    dpairData->userCtx = ctx;\r
 \r
     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};\r
     cbData.cb = DirectPairingHandler;\r
@@ -950,9 +959,6 @@ OCStackResult DPDeviceDiscovery(unsigned short waittime)
     }\r
 \r
     OCStackResult ret;\r
-    struct timespec startTime = {.tv_sec=0, .tv_nsec=0};\r
-    struct timespec currTime  = {.tv_sec=0, .tv_nsec=0};\r
-    struct timespec timeout;\r
 \r
     const char DP_DISCOVERY_QUERY[] = "/oic/sec/pconf";\r
 \r
@@ -973,13 +979,17 @@ OCStackResult DPDeviceDiscovery(unsigned short waittime)
     }\r
 \r
     // wait..\r
-    timeout.tv_sec  = 0;\r
-    timeout.tv_nsec = 100000000L;\r
 \r
     int clock_res = -1;\r
+#if defined(_MSC_VER)\r
+    time_t startTime = NULL;\r
+    clock_res = (time(&startTime) == -1);\r
+#else\r
+    struct timespec startTime = {.tv_sec=0, .tv_nsec=0};\r
 #if defined(__ANDROID__) || _POSIX_TIMERS > 0\r
     clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);\r
 #endif\r
+#endif\r
     if (0 != clock_res)\r
     {\r
         OIC_LOG(ERROR, TAG, "clock error");\r
@@ -992,27 +1002,39 @@ OCStackResult DPDeviceDiscovery(unsigned short waittime)
 \r
     while (1)\r
     {\r
+#if defined(_MSC_VER)\r
+        time_t currTime = NULL;\r
+        clock_res = (time(&currTime) == -1);\r
+#else\r
+        struct timespec currTime  = {.tv_sec=0, .tv_nsec=0};\r
 #if defined(__ANDROID__) || _POSIX_TIMERS > 0\r
         clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);\r
 #endif\r
+#endif\r
         if (0 != clock_res)\r
         {\r
             OIC_LOG(ERROR, TAG, "clock error");\r
             ret = OC_STACK_ERROR;\r
             break;\r
         }\r
+#if defined(_MSC_VER)\r
+        long elapsed = currTime - startTime;\r
+#else\r
         long elapsed = (currTime.tv_sec - startTime.tv_sec);\r
+#endif\r
         if (elapsed > waittime)\r
         {\r
             break;\r
         }\r
         else\r
         {\r
+            struct timespec timeout = {.tv_sec=0, .tv_nsec=100000000L};\r
+            OCProcess();\r
             nanosleep(&timeout, NULL);\r
         }\r
     }\r
 \r
-    //Waiting for each response.\r
+    // Waiting for each response.\r
     ret = OCCancel(handle, OC_LOW_QOS, NULL, 0);\r
     if (OC_STACK_OK != ret)\r
     {\r
index 19c1244..47c7c59 100644 (file)
@@ -60,7 +60,7 @@ static const uint16_t CBOR_SIZE = 512;
 static const uint16_t CBOR_MAX_SIZE = 4400;
 
 /** DOXM Map size - Number of mandatory items. */
-static const uint8_t DOXM_MAP_SIZE = 7;
+static const uint8_t DOXM_MAP_SIZE = 9;
 
 static OicSecDoxm_t        *gDoxm = NULL;
 static OCResourceHandle    gDoxmHandle = NULL;
@@ -231,13 +231,45 @@ OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, siz
     OICFree(strUuid);
     strUuid = NULL;
 
-    //DPC -- not Mandatory, but this type is boolean, so instance always has a value.
+    //x.com.samsung.dpc -- not Mandatory(vendor-specific), but this type is boolean, so instance always has a value.
     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DPC_NAME,
         strlen(OIC_JSON_DPC_NAME));
     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Tag.");
     cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->dpc);
     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Value.");
 
+    //RT -- Mandatory
+    CborEncoder rtArray;
+    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
+            strlen(OIC_JSON_RT_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
+    cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
+    for (size_t i = 0; i < 1; i++)
+    {
+        cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
+                strlen(OIC_RSRC_TYPE_SEC_DOXM));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
+    }
+    cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
+
+    //IF-- Mandatory
+     CborEncoder ifArray;
+     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
+             strlen(OIC_JSON_IF_NAME));
+     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
+     cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
+     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
+    for (size_t i = 0; i < 1; i++)
+    {
+        cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
+                strlen(OC_RSRVD_INTERFACE_DEFAULT));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
+    }
+    cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
+
     cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
 
@@ -313,7 +345,7 @@ OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
 
         int i = 0;
         size_t len = 0;
-        while (cbor_value_is_valid(&oxmType))
+        while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
         {
             cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
                                                         &len, NULL);
@@ -339,7 +371,7 @@ OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
 
         int i = 0;
-        while (cbor_value_is_valid(&oxm))
+        while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
         {
             cborFindResult = cbor_value_get_int(&oxm, (int *) &doxm->oxm[i++]);
             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
@@ -496,6 +528,8 @@ static bool ValidateQuery(const char * query)
     bool bOwnedMatch = false;       // does 'owned' query value matches with doxm.owned status?
     bool bDeviceIDQry = false;      // does querystring contains 'deviceid' query ?
     bool bDeviceIDMatch = false;    // does 'deviceid' query matches with doxm.deviceid ?
+    bool bInterfaceQry = false;      // does querystring contains 'if' query ?
+    bool bInterfaceMatch = false;    // does 'if' query matches with oic.if.baseline ?
 
     OicParseQueryIter_t parseIter = {.attrPos = NULL};
 
@@ -529,6 +563,16 @@ static bool ValidateQuery(const char * query)
                 bDeviceIDMatch = true;
             }
         }
+
+        if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
+        {
+            bInterfaceQry = true;
+            if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
+            {
+                bInterfaceMatch = true;
+            }
+            return (bInterfaceQry ? bInterfaceMatch: true);
+        }
     }
 
     return ((bOwnedQry ? bOwnedMatch : true) && (bDeviceIDQry ? bDeviceIDMatch : true));
@@ -543,6 +587,7 @@ static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest
     //Checking if Get request is a query.
     if (ehRequest->query)
     {
+        OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
         OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
         if (!ValidateQuery(ehRequest->query))
         {
@@ -563,7 +608,7 @@ static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest
     {
         if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size))
         {
-            payload = NULL;
+            OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
         }
     }
 
@@ -579,11 +624,12 @@ static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest
     return ehRet;
 }
 
-static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest * ehRequest)
 {
-    OIC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing PUT request");
+    OIC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing POST request");
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
     OicUuid_t emptyOwner = {.id = {0} };
+    static uint16_t previousMsgId = 0;
 
     /*
      * Convert CBOR Doxm data into binary. This will also validate
@@ -683,25 +729,29 @@ static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest *
                         caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
 
-                        char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
-                        if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
+                        if(previousMsgId != ehRequest->messageID)
                         {
-                            //Set the device id to derive temporal PSK
-                            SetUuidForRandomPinOxm(&gDoxm->deviceID);
-
-                            /**
-                             * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
-                             * Credential should not be saved into SVR.
-                             * For this reason, use a temporary get_psk_info callback to random PIN OxM.
-                             */
-                            caRes = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm);
-                            VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
-                            ehRet = OC_EH_OK;
-                        }
-                        else
-                        {
-                            OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
-                            ehRet = OC_EH_ERROR;
+                            char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
+                            if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
+                            {
+                                //Set the device id to derive temporal PSK
+                                SetUuidForRandomPinOxm(&gDoxm->deviceID);
+
+                                /**
+                                 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
+                                 * Credential should not be saved into SVR.
+                                 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
+                                 */
+                                caRes = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm);
+                                VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
+                                ehRet = OC_EH_OK;
+                            }
+                            else
+                            {
+                                OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
+                                ehRet = OC_EH_ERROR;
+                            }
+                            previousMsgId = ehRequest->messageID;
                         }
 #endif //__WITH_DTLS__
                     }
@@ -778,8 +828,8 @@ static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest *
                 // Update new state in persistent storage
                 if (UpdatePersistentStorage(gDoxm))
                 {
-                    //Update default ACL of security resource to prevent anonymous user access.
-                    if(OC_STACK_OK == UpdateDefaultSecProvACL())
+                    //Update default ACE of security resource to prevent anonymous user access.
+                    if(OC_STACK_OK == UpdateDefaultSecProvACE())
                     {
                         ehRet = OC_EH_OK;
                     }
@@ -845,8 +895,8 @@ OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
                 ehRet = HandleDoxmGetRequest(ehRequest);
                 break;
 
-            case OC_REST_PUT:
-                ehRet = HandleDoxmPutRequest(ehRequest);
+            case OC_REST_POST:
+                ehRet = HandleDoxmPostRequest(ehRequest);
                 break;
 
             default:
@@ -863,12 +913,12 @@ OCStackResult CreateDoxmResource()
 {
     OCStackResult ret = OCCreateResource(&gDoxmHandle,
                                          OIC_RSRC_TYPE_SEC_DOXM,
-                                         OIC_MI_DEF,
+                                         OC_RSRVD_INTERFACE_DEFAULT,
                                          OIC_RSRC_DOXM_URI,
                                          DoxmEntityHandler,
                                          NULL,
-                                         OC_OBSERVABLE | OC_SECURE |
-                                         OC_EXPLICIT_DISCOVERABLE);
+                                         OC_SECURE |
+                                         OC_DISCOVERABLE);
 
     if (OC_STACK_OK != ret)
     {
old mode 100755 (executable)
new mode 100644 (file)
index 0c5c03f..830090a
@@ -42,9 +42,7 @@
 #include "ocpayload.h"
 #include "payload_logging.h"
 #include <stdlib.h>
-#ifdef WITH_ARDUINO
-#include <string.h>
-#else
+#ifdef HAVE_STRINGS_H
 #include <strings.h>
 #endif
 
@@ -136,7 +134,7 @@ OCStackResult SavePairingPSK(OCDevAddr *endpoint,
     }
 
     uint8_t pairingPSK[OWNER_PSK_LENGTH_128] = {0};
-    OicSecKey_t pairingKey = {pairingPSK, OWNER_PSK_LENGTH_128};
+    OicSecKey_t pairingKey = {pairingPSK, OWNER_PSK_LENGTH_128, OIC_ENCODING_RAW};
 
     //Generating PairingPSK using OwnerPSK scheme
     CAResult_t pskRet = CAGenerateOwnerPSK((const CAEndpoint_t *)endpoint,
@@ -297,7 +295,7 @@ OCStackResult CBORPayloadToDpair(const uint8_t *cborPayload, size_t size,
     dpair = (OicSecDpairing_t *)OICCalloc(1, sizeof(*dpair));
     VERIFY_NON_NULL(TAG, dpair, ERROR);
 
-    while (cbor_value_is_valid(&dpairMap))
+    while (cbor_value_is_valid(&dpairMap) && cbor_value_is_text_string(&dpairMap))
     {
         char *name = NULL;
         size_t len = 0;
@@ -308,7 +306,7 @@ OCStackResult CBORPayloadToDpair(const uint8_t *cborPayload, size_t size,
         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing a value in DPair map");
 
         type = cbor_value_get_type(&dpairMap);
-        if (0 == strcmp(OIC_JSON_SPM_NAME, name))
+        if (0 == strcmp(OIC_JSON_SPM_NAME, name) && cbor_value_is_integer(&dpairMap))
         {
             cborFindResult = cbor_value_get_int(&dpairMap, (int *) &dpair->spm);
             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SPM Value");
@@ -559,24 +557,84 @@ static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequ
         OicSecPdAcl_t *pdAcl;
         LL_FOREACH(pconf->pdacls, pdAcl)
         {
-            OicSecAcl_t acl;
-            memset(&acl, 0, sizeof(OicSecAcl_t));
-            memcpy(&acl.subject, &gDpair->pdeviceID, sizeof(OicUuid_t));
-            acl.resources = pdAcl->resources;
-            acl.resourcesLen = pdAcl->resourcesLen;
-            memcpy(&acl.rownerID, &pconf->rownerID, sizeof(OicUuid_t));
-            acl.permission = pdAcl->permission;
-            acl.periods = pdAcl->periods;
-            acl.recurrences = pdAcl->recurrences;
-            acl.prdRecrLen = pdAcl->prdRecrLen;
+            OicSecAcl_t* acl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
+            VERIFY_NON_NULL(TAG, acl, ERROR);
+
+            OicSecAce_t* ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+            VERIFY_NON_NULL(TAG, ace, ERROR);
+
+            LL_APPEND(acl->aces, ace);
+
+            memcpy(&ace->subjectuuid, &gDpair->pdeviceID, sizeof(OicUuid_t));
+
+            for(size_t i = 0; i < pdAcl->resourcesLen; i++)
+            {
+                OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+                VERIFY_NON_NULL(TAG, rsrc, ERROR);
+                LL_APPEND(ace->resources, rsrc);
+
+                //href
+                rsrc->href = OICStrdup(pdAcl->resources[i]);
+
+                // TODO: Append 'if' and 'rt' as workaround
+                // if
+                rsrc->interfaceLen = 1;
+                rsrc->interfaces = (char**)OICCalloc(rsrc->interfaceLen, sizeof(char));
+                VERIFY_NON_NULL(TAG, (rsrc->interfaces), ERROR);
+                rsrc->interfaces[0] = OICStrdup(OC_RSRVD_INTERFACE_DEFAULT);
+                VERIFY_NON_NULL(TAG, (rsrc->interfaces[0]), ERROR);
+
+                //rt
+                rsrc->typeLen = 1;
+                rsrc->types = (char**)OICCalloc(rsrc->typeLen, sizeof(char));
+                VERIFY_NON_NULL(TAG, (rsrc->types), ERROR);
+                rsrc->types[0] = OICStrdup("oic.core");
+                VERIFY_NON_NULL(TAG, (rsrc->types[0]), ERROR);
+            }
+
+            ace->permission = pdAcl->permission;
+
+            //Copy the validity
+            if(pdAcl->periods || pdAcl->recurrences)
+            {
+                OicSecValidity_t* validity = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+                VERIFY_NON_NULL(TAG, validity, ERROR);
+
+                if(pdAcl->periods && pdAcl->periods[0])
+                {
+                    size_t periodLen = strlen(pdAcl->periods[0]) + 1;
+                    validity->period = (char*)OICMalloc(periodLen * sizeof(char));
+                    VERIFY_NON_NULL(TAG, (validity->period), ERROR);
+                    OICStrcpy(validity->period, periodLen, pdAcl->periods[0]);
+                }
+
+                if(pdAcl->recurrences && 0 < pdAcl->prdRecrLen)
+                {
+                    validity->recurrenceLen = pdAcl->prdRecrLen;
+                    validity->recurrences = (char**)OICMalloc(sizeof(char*) * pdAcl->prdRecrLen);
+                    VERIFY_NON_NULL(TAG, (validity->recurrences), ERROR);
+
+                    for(size_t i = 0; i < pdAcl->prdRecrLen; i++)
+                    {
+                        size_t recurrenceLen = strlen(pdAcl->recurrences[i]) + 1;
+                        validity->recurrences[i] = (char*)OICMalloc(recurrenceLen  * sizeof(char));
+                        VERIFY_NON_NULL(TAG, (validity->recurrences[i]), ERROR);
+
+                        OICStrcpy(validity->recurrences[i], recurrenceLen, pdAcl->recurrences[i]);
+                    }
+                }
+
+                LL_APPEND(ace->validities, validity);
+            }
 
             size_t size = 0;
             uint8_t *payload = NULL;
-            if (OC_STACK_OK == AclToCBORPayload(&acl, &payload, &size))
+            if (OC_STACK_OK == AclToCBORPayload(acl, &payload, &size))
             {
                 InstallNewACL(payload, size);
                 OICFree(payload);
             }
+            DeleteACLList(acl);
         }
 
         //update pconf device list
@@ -657,7 +715,7 @@ OCStackResult CreateDpairingResource()
 
     ret = OCCreateResource(&gDpairHandle,
                            OIC_RSRC_TYPE_SEC_DPAIRING,
-                           OIC_MI_DEF,
+                           OC_RSRVD_INTERFACE_DEFAULT,
                            OIC_RSRC_DPAIRING_URI,
                            DpairingEntityHandler,
                            NULL,
index d3b6cb1..dc16f4b 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 //Not supported on Arduino due lack of absolute time need to implement iCalendar
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO)
 
 #define _XOPEN_SOURCE  //Needed by strptime
 #include <string.h>
 #include "iotvticalendar.h"
 #include "oic_string.h"
 
+#ifndef HAVE_STRPTIME
+char *strptime(const char *buf, const char *fmt, struct tm *tm);
+#endif
+
 static char dtFormat[] =  "%Y%m%dT%H%M%S"; //date-time format
 static char dFormat[] =  "%Y%m%d";         // date format
 
index 02c984a..785234a 100644 (file)
@@ -20,6 +20,7 @@
 
 #include <string.h>
 #include <math.h>
+#include "platform_features.h"
 #include "pbkdf2.h"
 #include "hmac.h"
 #include "debug.h"
index 921b249..0026762 100644 (file)
@@ -39,9 +39,7 @@
 #include <stdlib.h>
 #include "psinterface.h"
 #include "security_internals.h"
-#ifdef WITH_ARDUINO
-#include <string.h>
-#else
+#ifdef HAVE_STRINGS_H
 #include <strings.h>
 #endif
 
@@ -476,7 +474,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
         char *name = NULL;
         size_t len = 0;
         CborType type = cbor_value_get_type(&pconfMap);
-        if (type == CborTextStringType)
+        if (type == CborTextStringType && cbor_value_is_text_string(&pconfMap))
         {
             cborFindResult = cbor_value_dup_text_string(&pconfMap, &name, &len, NULL);
             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
@@ -487,7 +485,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
         if (name)
         {
             //EDP -- Mandatory
-            if(0 == strcmp(OIC_JSON_EDP_NAME, name))
+            if(0 == strcmp(OIC_JSON_EDP_NAME, name) && cbor_value_is_boolean(&pconfMap))
             {
                 cborFindResult = cbor_value_get_boolean(&pconfMap, &pconf->edp);
                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
@@ -505,7 +503,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                 cborFindResult = cbor_value_enter_container(&pconfMap, &prm);
                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to eneter array");
 
-                while (cbor_value_is_valid(&prm))
+                while (cbor_value_is_valid(&prm) && cbor_value_is_integer(&prm))
                 {
                     cborFindResult = cbor_value_get_int(&prm, (int *)&pconf->prm[i++]);
                     VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
@@ -514,7 +512,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                 }
             }
             //PIN -- Mandatory
-            if (0 == strcmp(OIC_JSON_PIN_NAME, name))
+            if (0 == strcmp(OIC_JSON_PIN_NAME, name) && cbor_value_is_byte_string(&pconfMap))
             {
                 uint8_t *pin = NULL;
                 cborFindResult = cbor_value_dup_byte_string(&pconfMap, &pin, &len, NULL);
@@ -546,7 +544,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                         char* name = NULL;
                         size_t len = 0;
                         CborType type = cbor_value_get_type(&pdAclMap);
-                        if (type == CborTextStringType)
+                        if (type == CborTextStringType && cbor_value_is_text_string(&pdAclMap))
                         {
                             cborFindResult = cbor_value_dup_text_string(&pdAclMap, &name,
                                     &len, NULL);
@@ -557,7 +555,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                         if (name)
                         {
                             // Resources -- Mandatory
-                            if (strcmp(name, OIC_JSON_RESOURCES_NAME) == 0)
+                            if (strcmp(name, OIC_JSON_RESOURCES_NAME) == 0 && cbor_value_is_array(&pdAclMap))
                             {
                                 int i = 0;
                                 CborValue resources = { .parser = NULL };
@@ -576,7 +574,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                                     cborFindResult = cbor_value_enter_container(&resources, &rMap);
                                     VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Resource Map");
 
-                                    while(cbor_value_is_valid(&rMap))
+                                    while(cbor_value_is_valid(&rMap) && cbor_value_is_text_string(&rMap))
                                     {
                                         char *rMapName = NULL;
                                         size_t rMapNameLen = 0;
@@ -640,15 +638,16 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                             }
 
                             // Permissions -- Mandatory
-                            if (strcmp(name, OIC_JSON_PERMISSION_NAME) == 0)
+                            if (strcmp(name, OIC_JSON_PERMISSION_NAME) == 0 && cbor_value_is_unsigned_integer(&pdAclMap))
                             {
-                                cborFindResult = cbor_value_get_uint64(&pdAclMap,
-                                        (uint64_t *) &pdacl->permission);
+                                uint64_t permission = 0;
+                                cborFindResult = cbor_value_get_uint64(&pdAclMap, &permission);
+                                pdacl->permission = (uint16_t)permission;
                                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
                             }
 
                             // Period -- Not mandatory
-                            if (strcmp(name, OIC_JSON_PERIODS_NAME) == 0)
+                            if (strcmp(name, OIC_JSON_PERIODS_NAME) == 0 && cbor_value_is_array(&pdAclMap))
                             {
                                 int i = 0;
                                 CborValue period = { .parser = NULL };
@@ -660,7 +659,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                                 pdacl->periods = (char **) OICCalloc(pdacl->prdRecrLen, sizeof(char*));
                                 VERIFY_NON_NULL(TAG, pdacl->periods, ERROR);
 
-                                while (cbor_value_is_text_string(&period))
+                                while (cbor_value_is_text_string(&period) && cbor_value_is_text_string(&period))
                                 {
                                     cborFindResult = cbor_value_dup_text_string(&period,
                                             &pdacl->periods[i++], &len, NULL);
@@ -672,7 +671,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                             }
 
                             // Recurrence -- Not mandatory
-                            if (strcmp(name, OIC_JSON_RECURRENCES_NAME) == 0)
+                            if (strcmp(name, OIC_JSON_RECURRENCES_NAME) == 0 && cbor_value_is_array(&pdAclMap))
                             {
                                 int i = 0;
                                 CborValue recurrences = { .parser = NULL };
@@ -683,7 +682,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                                 pdacl->recurrences = (char **) OICCalloc(pdacl->prdRecrLen, sizeof(char*));
                                 VERIFY_NON_NULL(TAG, pdacl->recurrences, ERROR);
 
-                                while (cbor_value_is_text_string(&recurrences))
+                                while (cbor_value_is_text_string(&recurrences) && cbor_value_is_text_string(&recurrences))
                                 {
                                     cborFindResult = cbor_value_dup_text_string(&recurrences,
                                             &pdacl->recurrences[i++], &len, NULL);
@@ -725,7 +724,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
             }
 
             //PDDev -- Mandatory
-            if (strcmp(name, OIC_JSON_PDDEV_LIST_NAME) == 0)
+            if (strcmp(name, OIC_JSON_PDDEV_LIST_NAME) == 0 && cbor_value_is_array(&pconfMap))
             {
                 int i = 0;
                 CborValue pddevs = { .parser = NULL };
@@ -736,7 +735,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
 
                 pconf->pddevs = (OicUuid_t *)OICMalloc(pconf->pddevLen * sizeof(OicUuid_t));
                 VERIFY_NON_NULL(TAG, pconf->pddevs, ERROR);
-                while (cbor_value_is_valid(&pddevs))
+                while (cbor_value_is_valid(&pddevs) && cbor_value_is_text_string(&pddevs))
                 {
                     char *pddev = NULL;
                     cborFindResult = cbor_value_dup_text_string(&pddevs, &pddev, &len, NULL);
@@ -750,7 +749,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
             }
 
             //Mandatory - Device Id
-            if (0 == strcmp(OIC_JSON_DEVICE_ID_NAME, name))
+            if (0 == strcmp(OIC_JSON_DEVICE_ID_NAME, name) && cbor_value_is_text_string(&pconfMap))
             {
                 char *deviceId = NULL;
                 cborFindResult = cbor_value_dup_text_string(&pconfMap, &deviceId, &len, NULL);
@@ -761,7 +760,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
             }
 
             // ROwner -- Mandatory
-            if (0 == strcmp(OIC_JSON_ROWNERID_NAME, name))
+            if (0 == strcmp(OIC_JSON_ROWNERID_NAME, name) && cbor_value_is_text_string(&pconfMap))
             {
                 char *rowner = NULL;
                 cborFindResult = cbor_value_dup_text_string(&pconfMap, &rowner, &len, NULL);
@@ -1010,7 +1009,7 @@ OCStackResult CreatePconfResource()
 
     ret = OCCreateResource(&gPconfHandle,
                            OIC_RSRC_TYPE_SEC_PCONF,
-                           OIC_MI_DEF,
+                           OC_RSRVD_INTERFACE_DEFAULT,
                            OIC_RSRC_PCONF_URI,
                            PconfEntityHandler,
                            NULL,
index 4a4694d..04451b0 100644 (file)
@@ -19,6 +19,7 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 #include <string.h>
 
+#include "utlist.h"
 #include "oic_malloc.h"
 #include "policyengine.h"
 #include "amsmgr.h"
@@ -214,9 +215,9 @@ bool IsRequestFromResourceOwner(PEContext_t *context)
     return retVal;
 }
 
-inline static bool IsRequestSubjectEmpty(PEContext_t *context)
+INLINE_API bool IsRequestSubjectEmpty(PEContext_t *context)
 {
-    OicUuid_t emptySubject = {.id={}};
+    OicUuid_t emptySubject = {.id={0}};
 
     if(NULL == context)
     {
@@ -235,7 +236,7 @@ inline static bool IsRequestSubjectEmpty(PEContext_t *context)
  *
  * @return true if 'permission' bits include all 'request' bits.
  */
-static inline bool IsPermissionAllowingRequest(const uint16_t permission,
+INLINE_API bool IsPermissionAllowingRequest(const uint16_t permission,
     const uint16_t request)
 {
     if (request == (request & permission))
@@ -253,7 +254,7 @@ static inline bool IsPermissionAllowingRequest(const uint16_t permission,
  *
  * @return true if 'subject' is the wildcard, false if it is not.
  */
-static inline bool IsWildCardSubject(OicUuid_t *subject)
+INLINE_API bool IsWildCardSubject(OicUuid_t *subject)
 {
     if(NULL == subject)
     {
@@ -308,28 +309,32 @@ static void CopyParamsToContext(PEContext_t     *context,
  * @return true if access is within valid time period or if the period or recurrence is not present.
  * false if period and recurrence present and the access is not within valid time period.
  */
-static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
+static bool IsAccessWithinValidTime(const OicSecAce_t *ace)
 {
 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
-                     //lack of absolute time
-    if (NULL== acl || NULL == acl->periods || 0 == acl->prdRecrLen)
+    //lack of absolute time
+    if (NULL== ace || NULL == ace->validities)
     {
         return true;
     }
 
     //periods & recurrences rules are paired.
-    if (NULL == acl->recurrences)
+    if (NULL == ace->validities->recurrences)
     {
         return false;
     }
 
-    for (size_t i = 0; i < acl->prdRecrLen; i++)
+    OicSecValidity_t* validity =  NULL;
+    LL_FOREACH(ace->validities, validity)
     {
-        if (IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(acl->periods[i],
-            acl->recurrences[i]))
+        for(size_t i = 0; i < validity->recurrenceLen; i++)
         {
-            OIC_LOG(INFO, TAG, "Access request is in allowed time period");
-            return true;
+            if (IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(validity->period,
+                validity->recurrences[i]))
+            {
+                OIC_LOG(INFO, TAG, "Access request is in allowed time period");
+                return true;
+            }
         }
     }
     OIC_LOG(ERROR, TAG, "Access request is in invalid time period");
@@ -341,24 +346,25 @@ static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
 }
 
 /**
- * Check whether 'resource' is in the passed ACL.
+ * Check whether 'resource' is in the passed ACE.
  *
  * @param resource is the resource being searched.
- * @param acl is the ACL to check.
+ * @param ace is the ACE to check.
  *
  * @return true if 'resource' found, otherwise false.
  */
- static bool IsResourceInAcl(const char *resource, const OicSecAcl_t *acl)
+ static bool IsResourceInAce(const char *resource, const OicSecAce_t *ace)
 {
-    if (NULL== acl || NULL == resource)
+    if (NULL== ace || NULL == resource)
     {
         return false;
     }
 
-     for (size_t n = 0; n < acl->resourcesLen; n++)
-     {
-         if (0 == strcmp(resource, acl->resources[n]) || // TODO null terms?
-             0 == strcmp(WILDCARD_RESOURCE_URI, acl->resources[n]))
+    OicSecRsrc_t* rsrc = NULL;
+    LL_FOREACH(ace->resources, rsrc)
+    {
+         if (0 == strcmp(resource, rsrc->href) || // TODO null terms?
+             0 == strcmp(WILDCARD_RESOURCE_URI, rsrc->href))
          {
              return true;
          }
@@ -381,8 +387,8 @@ static void ProcessAccessRequest(PEContext_t *context)
     OIC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
     if (NULL != context)
     {
-        const OicSecAcl_t *currentAcl = NULL;
-        OicSecAcl_t *savePtr = NULL;
+        const OicSecAce_t *currentAce = NULL;
+        OicSecAce_t *savePtr = NULL;
 
         // Start out assuming subject not found.
         context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
@@ -391,28 +397,28 @@ static void ProcessAccessRequest(PEContext_t *context)
         // ACL for this request.
         do
         {
-            OIC_LOG_V(DEBUG, TAG, "%s: getting ACL..." ,__func__);
-            currentAcl = GetACLResourceData(&context->subject, &savePtr);
+            OIC_LOG_V(DEBUG, TAG, "%s: getting ACE..." ,__func__);
+            currentAce = GetACLResourceData(&context->subject, &savePtr);
 
-            if (NULL != currentAcl)
+            if (NULL != currentAce)
             {
                 // Found the subject, so how about resource?
-                OIC_LOG_V(DEBUG, TAG, "%s:found ACL matching subject" ,__func__);
+                OIC_LOG_V(DEBUG, TAG, "%s:found ACE matching subject" ,__func__);
 
                 // Subject was found, so err changes to Rsrc not found for now.
                 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
                 OIC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
-                if (IsResourceInAcl(context->resource, currentAcl))
+                if (IsResourceInAce(context->resource, currentAce))
                 {
-                    OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACL" ,__func__);
+                    OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACE" ,__func__);
                     context->matchingAclFound = true;
 
                     // Found the resource, so it's down to valid period & permission.
                     context->retVal = ACCESS_DENIED_INVALID_PERIOD;
-                    if (IsAccessWithinValidTime(currentAcl))
+                    if (IsAccessWithinValidTime(currentAce))
                     {
                         context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
-                        if (IsPermissionAllowingRequest(currentAcl->permission, context->permission))
+                        if (IsPermissionAllowingRequest(currentAce->permission, context->permission))
                         {
                             context->retVal = ACCESS_GRANTED;
                         }
@@ -423,7 +429,7 @@ static void ProcessAccessRequest(PEContext_t *context)
             {
                 OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
             }
-        } while ((NULL != currentAcl) && (false == context->matchingAclFound));
+        } while ((NULL != currentAce) && (false == context->matchingAclFound));
 
         if (IsAccessGranted(context->retVal))
         {
@@ -476,7 +482,7 @@ SRMAccessResponse_t CheckPermission(PEContext_t     *context,
         // Else request is a "normal" request that must be tested against ACL
         else
         {
-            OicUuid_t saveSubject = {.id={}};
+            OicUuid_t saveSubject = {.id={0}};
             bool isSubEmpty = IsRequestSubjectEmpty(context);
 
             ProcessAccessRequest(context);
index c10b097..d263892 100644 (file)
 #define TAG  "SRM-PSI"
 
 //SVR database buffer block size
+#ifdef _WIN32
+#define DB_FILE_SIZE_BLOCK 1023
+#else
 const size_t DB_FILE_SIZE_BLOCK = 1023;
+#endif
 
 /**
  * Gets the Secure Virtual Database size
index b3e63ac..39d1d26 100644 (file)
@@ -42,7 +42,7 @@ static const uint16_t CBOR_SIZE = 512;
 static const uint16_t CBOR_MAX_SIZE = 4400;
 
 // PSTAT Map size - Number of mandatory items
-static const uint8_t PSTAT_MAP_SIZE = 7;
+static const uint8_t PSTAT_MAP_SIZE = 9;
 
 static OicSecDpom_t gSm = SINGLE_SERVICE_CLIENT_DRIVEN;
 static OicSecPstat_t gDefaultPstat =
@@ -157,6 +157,38 @@ OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **payload,
     OICFree(strUuid);
     strUuid = NULL;
 
+    //RT -- Mandatory
+    CborEncoder rtArray;
+    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_RT_NAME,
+            strlen(OIC_JSON_RT_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
+    cborEncoderResult = cbor_encoder_create_array(&pstatMap, &rtArray, 1);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
+    for (size_t i = 0; i < 1; i++)
+    {
+        cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_PSTAT,
+                strlen(OIC_RSRC_TYPE_SEC_PSTAT));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
+    }
+    cborEncoderResult = cbor_encoder_close_container(&pstatMap, &rtArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
+
+    //IF-- Mandatory
+     CborEncoder ifArray;
+     cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_IF_NAME,
+             strlen(OIC_JSON_IF_NAME));
+     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
+     cborEncoderResult = cbor_encoder_create_array(&pstatMap, &ifArray, 1);
+     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
+    for (size_t i = 0; i < 1; i++)
+    {
+        cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
+                strlen(OC_RSRVD_INTERFACE_DEFAULT));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
+    }
+    cborEncoderResult = cbor_encoder_close_container(&pstatMap, &ifArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
+
     cborEncoderResult = cbor_encoder_close_container(&encoder, &pstatMap);
     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Closing PSTAT Map.");
 
@@ -318,21 +350,70 @@ static bool UpdatePersistentStorage(OicSecPstat_t *pstat)
     return bRet;
 }
 
+static bool ValidateQuery(const char * query)
+{
+    OIC_LOG (DEBUG, TAG, "In ValidateQuery");
+    if(NULL == gPstat)
+    {
+        return false;
+    }
+
+    bool bInterfaceQry = false;      // does querystring contains 'if' query ?
+    bool bInterfaceMatch = false;    // does 'if' query matches with oic.if.baseline ?
+
+    OicParseQueryIter_t parseIter = {.attrPos = NULL};
+
+    ParseQueryIterInit((unsigned char*)query, &parseIter);
+
+    while (GetNextQuery(&parseIter))
+    {
+        if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
+        {
+            bInterfaceQry = true;
+            if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
+            {
+                bInterfaceMatch = true;
+            }
+        }
+    }
+    return (bInterfaceQry ? bInterfaceMatch: true);
+}
 
 /**
  * The entity handler determines how to process a GET request.
  */
 static OCEntityHandlerResult HandlePstatGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
+    OCEntityHandlerResult ehRet = OC_EH_OK;
+
     OIC_LOG(INFO, TAG, "HandlePstatGetRequest  processing GET request");
 
-    // Convert ACL data into CBOR for transmission
+    //Checking if Get request is a query.
+    if (ehRequest->query)
+    {
+        OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
+        OIC_LOG(DEBUG, TAG, "HandlePstatGetRequest processing query");
+        if (!ValidateQuery(ehRequest->query))
+        {
+            ehRet = OC_EH_ERROR;
+        }
+    }
+
+    /*
+     * For GET or Valid Query request return doxm resource CBOR payload.
+     * For non-valid query return NULL json payload.
+     * A device will 'always' have a default Pstat, so PstatToCBORPayload will
+     * return valid pstat resource json.
+     */
     size_t size = 0;
     uint8_t *payload = NULL;
-    OCStackResult res = PstatToCBORPayload(gPstat, &payload, &size);
-
-    // A device should always have a default pstat. Therefore, payload should never be NULL.
-    OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
+    if (ehRet == OC_EH_OK)
+    {
+        if(OC_STACK_OK != PstatToCBORPayload(gPstat, &payload, &size))
+        {
+            OIC_LOG(WARNING, TAG, "PstatToCBORPayload failed in HandlePstatGetRequest");
+        }
+    }
 
     // Send response payload to request originator
     if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, payload, size))
@@ -350,10 +431,10 @@ static OCEntityHandlerResult HandlePstatGetRequest (const OCEntityHandlerRequest
  * resource or create a new resource.
  * For pstat, it updates only tm and om.
  */
-static OCEntityHandlerResult HandlePstatPutRequest(const OCEntityHandlerRequest *ehRequest)
+static OCEntityHandlerResult HandlePstatPostRequest(const OCEntityHandlerRequest *ehRequest)
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    OIC_LOG(INFO, TAG, "HandlePstatPutRequest  processing PUT request");
+    OIC_LOG(INFO, TAG, "HandlePstatPostRequest  processing POST request");
     OicSecPstat_t *pstat = NULL;
 
     if (ehRequest->payload)
@@ -441,8 +522,8 @@ static OCEntityHandlerResult HandlePstatPutRequest(const OCEntityHandlerRequest
             case OC_REST_GET:
                 ehRet = HandlePstatGetRequest(ehRequest);
                 break;
-            case OC_REST_PUT:
-                ehRet = HandlePstatPutRequest(ehRequest);
+            case OC_REST_POST:
+                ehRet = HandlePstatPostRequest(ehRequest);
                 break;
             default:
                 ehRet = OC_EH_ERROR;
@@ -460,11 +541,12 @@ static OCEntityHandlerResult HandlePstatPutRequest(const OCEntityHandlerRequest
 {
     OCStackResult ret = OCCreateResource(&gPstatHandle,
                                          OIC_RSRC_TYPE_SEC_PSTAT,
-                                         OIC_MI_DEF,
+                                         OC_RSRVD_INTERFACE_DEFAULT,
                                          OIC_RSRC_PSTAT_URI,
                                          PstatEntityHandler,
                                          NULL,
-                                         OC_RES_PROP_NONE);
+                                         OC_SECURE |
+                                         OC_DISCOVERABLE);
 
     if (OC_STACK_OK != ret)
     {
index 26a9277..10b46a8 100644 (file)
@@ -183,7 +183,8 @@ void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requ
 
     if (IsAccessGranted(response) && gRequestHandler)
     {
-        return (gRequestHandler(endPoint, requestInfo));
+        gRequestHandler(endPoint, requestInfo);
+        return;
     }
 
     // Form a 'Error', 'slow response' or 'access deny' response and send to peer
@@ -342,7 +343,7 @@ OCStackResult SRMInitPolicyEngine()
 
 void SRMDeInitPolicyEngine()
 {
-    return DeInitPolicyEngine(&g_policyEngineContext);
+    DeInitPolicyEngine(&g_policyEngineContext);
 }
 
 bool SRMIsSecurityResourceURI(const char* uri)
index d7b3c77..5414ef6 100644 (file)
 
 #include <stdlib.h>
 #include "securevirtualresourcetypes.h"
+#include "octypes.h"
 
 const char * SVR_DB_FILE_NAME = "oic_svr_db.json";
 const char * SVR_DB_DAT_FILE_NAME = "oic_svr_db.dat";
-const char * OIC_MI_DEF = "oic.mi.def";
 
 //AMACL
-const char * OIC_RSRC_TYPE_SEC_AMACL = "oic.sec.amacl";
+const char * OIC_RSRC_TYPE_SEC_AMACL = "oic.r.amacl";
 const char * OIC_RSRC_AMACL_URI =  "/oic/sec/amacl";
 const char * OIC_JSON_AMACL_NAME = "amacl";
 
 //ACL
-const char * OIC_RSRC_TYPE_SEC_ACL = "oic.sec.acl";
+const char * OIC_RSRC_TYPE_SEC_ACL = "oic.r.acl";
 const char * OIC_RSRC_ACL_URI =  "/oic/sec/acl";
 const char * OIC_JSON_ACL_NAME = "acl";
 const char * OIC_JSON_ACLIST_NAME = "aclist";
 const char * OIC_JSON_ACES_NAME = "aces";
 
 //Pstat
-const char * OIC_RSRC_TYPE_SEC_PSTAT = "oic.sec.pstat";
+const char * OIC_RSRC_TYPE_SEC_PSTAT = "oic.r.pstat";
 const char * OIC_RSRC_PSTAT_URI =  "/oic/sec/pstat";
 const char * OIC_JSON_PSTAT_NAME = "pstat";
 
 //doxm
-const char * OIC_RSRC_TYPE_SEC_DOXM = "oic.sec.doxm";
+const char * OIC_RSRC_TYPE_SEC_DOXM = "oic.r.doxm";
 const char * OIC_RSRC_DOXM_URI =  "/oic/sec/doxm";
 const char * OIC_JSON_DOXM_NAME = "doxm";
 
 //cred
-const char * OIC_RSRC_TYPE_SEC_CRED = "oic.sec.cred";
+const char * OIC_RSRC_TYPE_SEC_CRED = "oic.r.cred";
 const char * OIC_RSRC_CRED_URI =  "/oic/sec/cred";
 const char * OIC_JSON_CRED_NAME = "cred";
 const char * OIC_JSON_CREDS_NAME = "creds";
 
 //CRL
-const char * OIC_RSRC_TYPE_SEC_CRL = "oic.sec.crl";
+const char * OIC_RSRC_TYPE_SEC_CRL = "oic.r.crl";
 const char * OIC_RSRC_CRL_URI =  "/oic/sec/crl";
 const char * OIC_JSON_CRL_NAME = "crl";
 
 //SACL
-const char * OIC_RSRC_TYPE_SEC_SACL = "oic.sec.sacl";
+const char * OIC_RSRC_TYPE_SEC_SACL = "oic.r.sacl";
 const char * OIC_RSRC_SACL_URI =  "/oic/sec/sacl";
 const char * OIC_JSON_SACL_NAME = "sacl";
 
 //svc
-const char * OIC_RSRC_TYPE_SEC_SVC = "oic.sec.svc";
+const char * OIC_RSRC_TYPE_SEC_SVC = "oic.r.svc";
 const char * OIC_RSRC_SVC_URI =  "/oic/sec/svc";
 const char * OIC_JSON_SVC_NAME = "svc";
 
 //pconf
-const char * OIC_RSRC_TYPE_SEC_PCONF = "oic.sec.pconf";
+const char * OIC_RSRC_TYPE_SEC_PCONF = "oic.r.pconf";
 const char * OIC_RSRC_PCONF_URI =  "/oic/sec/pconf";
 const char * OIC_JSON_PCONF_NAME = "pconf";
 
 //dpairing
-const char * OIC_RSRC_TYPE_SEC_DPAIRING = "oic.sec.dpairing";
+const char * OIC_RSRC_TYPE_SEC_DPAIRING = "oic.r.dpairing";
 const char * OIC_RSRC_DPAIRING_URI =  "/oic/sec/dpairing";
 const char * OIC_JSON_DPAIRING_NAME = "dpairing";
 
 //version
-const char * OIC_RSRC_TYPE_SEC_VER = "oic.sec.ver";
+const char * OIC_RSRC_TYPE_SEC_VER = "oic.r.ver";
 const char * OIC_RSRC_VER_URI =  "/oic/sec/ver";
 const char * OIC_JSON_VER_NAME = "ver";
 
@@ -115,12 +115,13 @@ const char * OIC_JSON_PRIVDATA_NAME = "privdata";
 const char * OIC_JSON_OPTDATA_NAME = "optdata";
 const char * OIC_JSON_SERVICE_DEVICE_ID = "svcdid";
 const char * OIC_JSON_SERVICE_TYPE = "svct";
+const char* OIC_JSON_VALIDITY_NAME = "validity";
 const char * OIC_JSON_PERIOD_NAME = "period";
 const char * OIC_JSON_PERIODS_NAME = "prds";
 const char * OIC_JSON_CRMS_NAME = "crms";
 const char * OIC_JSON_RECURRENCES_NAME = "recurrence";
 const char * OIC_JSON_SUPPORTED_CRED_TYPE_NAME = "sct";
-const char * OIC_JSON_DPC_NAME = "dpc";
+const char * OIC_JSON_DPC_NAME = "x.com.samsung.dpc";
 const char * OIC_JSON_EDP_NAME = "edp";
 const char * OIC_JSON_PIN_NAME = "pin";
 const char * OIC_JSON_PDACL_NAME = "pdacl";
@@ -130,10 +131,10 @@ const char * OIC_JSON_PRM_NAME = "prm";
 const char * OIC_JSON_SPM_NAME = "spm";
 const char * OIC_JSON_PDEVICE_ID_NAME = "pdeviceuuid";
 const char * OIC_JSON_RLIST_NAME = "rlist";
-const char * OIC_JSON_HREF_NAME = "href";
-const char * OIC_JSON_REL_NAME = "rel";
-const char * OIC_JSON_RT_NAME = "rt";
-const char * OIC_JSON_IF_NAME = "if";
+const char * OIC_JSON_HREF_NAME = OC_RSRVD_HREF;
+const char * OIC_JSON_REL_NAME = OC_RSRVD_REL;
+const char * OIC_JSON_RT_NAME = OC_RSRVD_RESOURCE_TYPE;
+const char * OIC_JSON_IF_NAME = OC_RSRVD_INTERFACE;
 const char * OIC_JSON_ROWNERID_NAME = "rowneruuid";
 const char * OIC_JSON_ENCODING_NAME = "encoding";
 const char * OIC_JSON_DATA_NAME = "data";
index 1cc5694..dd56ded 100644 (file)
@@ -92,7 +92,7 @@ OCStackResult AddUuidArray(const cJSON* jsonRoot, const char* arrayItem,
 
     do
     {
-        unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+        unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {0};
         uint32_t outLen = 0;
         B64Result b64Ret = B64_OK;
 
diff --git a/resource/csdk/security/src/strptime.c b/resource/csdk/security/src/strptime.c
new file mode 100644 (file)
index 0000000..fd1b9bb
--- /dev/null
@@ -0,0 +1,141 @@
+/** @todo: Add Microsoft copyright */
+#include <stdio.h>
+#include <ctype.h>
+#include <time.h>
+#include <memory.h>
+#include <stdbool.h>
+
+#define TM_BASE_YEAR   1900
+
+static const int ydays[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
+
+bool is_leap_year(int yy)
+{
+    int yyyy = yy + TM_BASE_YEAR;
+
+    bool bLeap = false;
+    if (yyyy % 100 == 0)
+    {
+        return yyyy % 400 == 0;
+    }
+    return yyyy % 4 == 0;
+}
+
+
+char * strptime(const char *buf, const char *fmt, struct tm *tm)
+{
+    int temp = 0;
+    char c = '\0';
+
+    //check params
+    if ((fmt == NULL) || (tm == NULL))
+    {
+        return NULL;
+    }
+
+    //initialize the tm struct values
+    memset(tm, 0, sizeof(struct tm));
+    tm->tm_mday = 1;
+
+    while (buf && (c = *fmt++))
+    {
+        temp = 0;
+        if (c == '%')
+        {
+            switch (c = *fmt++)
+            {
+            case '%':
+                if (c != *buf++)
+                {
+                    return NULL;
+                }
+                break;
+
+            case 'd':   /* day of the month (1..31)*/
+                sscanf(buf, "%2d", &temp);
+                if (temp >= 1 && temp <= 31)
+                {
+                    tm->tm_mday = temp;
+                    buf += 2;
+                }
+                else
+                    return NULL;
+                break;
+
+            case 'H':   /* hour (0..23) */
+                sscanf(buf, "%2d", &temp);
+                if (temp >= 0 && temp <= 23)
+                {
+                    tm->tm_hour = temp;
+                    buf += 2;
+                }
+                else
+                    return NULL;
+                break;
+
+            case 'M':   /* minute (0..59) */
+                sscanf(buf, "%2d", &temp);
+                if (temp >= 0 && temp <= 59)
+                {
+                    tm->tm_min = temp;
+                    buf += 2;
+                }
+                else
+                    return NULL;
+                break;
+
+            case 'm':   /* month (1..12) */
+                sscanf(buf, "%2d", &temp);
+                if (temp >= 1 && temp <= 12)
+                {
+                    tm->tm_mon = temp - 1;
+                    buf += 2;
+                }
+                else
+                    return NULL;
+                break;
+
+            case 'S':   /* seconds (0..59) */
+                sscanf(buf, "%2d", &temp);
+                if (temp >= 0 && temp <= 59)
+                {
+                    tm->tm_sec = temp;
+                    buf += 2;
+                }
+                else
+                    return NULL;
+                break;
+
+            case 'Y':   /* year */
+                sscanf(buf, "%4d", &temp);
+                if (temp >= 0 && temp <= 9999)
+                {
+                    tm->tm_year = temp - TM_BASE_YEAR;
+                    buf += 4;
+                }
+                else
+                    return NULL;
+                break;
+
+            default:
+                return NULL;
+            }
+        }
+        else
+        {
+            if (c != *buf++)
+                return NULL;
+        }
+    }
+
+    //calculate tm_wday and tm_yday
+    tm->tm_yday = ydays[tm->tm_mon] + ((is_leap_year(tm->tm_year) && (tm->tm_mon >= 2)) ? 1 : 0) + tm->tm_mday - 1;
+
+    //1st Jan 1900 was Monday, hence weekday = the number of days from 1/1/1900  modulus 7 + 1
+    tm->tm_wday = (365 * tm->tm_year) + (tm->tm_year / 4) + tm->tm_yday + 1;        //1st Jan 1900 was Monday, hence add 1
+    if (is_leap_year(tm->tm_year))
+        tm->tm_wday--;
+    tm->tm_wday %= 7;
+
+    return (char*)buf;
+}
index a1175aa..9cb7f6b 100644 (file)
@@ -230,7 +230,7 @@ OCStackResult CBORPayloadToSVC(const uint8_t *cborPayload, size_t size,
 
             type = cbor_value_get_type(&svcMap);
             // Service Device Identity
-            if (0 == strcmp(OIC_JSON_SERVICE_DEVICE_ID, name))
+            if (0 == strcmp(OIC_JSON_SERVICE_DEVICE_ID, name) && cbor_value_is_byte_string(&svcMap))
             {
                 uint8_t *subjectId = NULL;
                 cborFindResult = cbor_value_dup_byte_string(&svcMap, &subjectId, &len, NULL);
@@ -239,14 +239,14 @@ OCStackResult CBORPayloadToSVC(const uint8_t *cborPayload, size_t size,
                 OICFree(subjectId);
             }
             // Service Type
-            if (0 == strcmp(OIC_JSON_SERVICE_TYPE, name))
+            if (0 == strcmp(OIC_JSON_SERVICE_TYPE, name) && cbor_value_is_integer(&svcMap))
             {
                 cborFindResult = cbor_value_get_int(&svcMap, (int *) &svc->svct);
                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find SVCT.");
             }
 
             // Owners -- Mandatory
-            if (0 == strcmp(OIC_JSON_OWNERS_NAME, name))
+            if (0 == strcmp(OIC_JSON_OWNERS_NAME, name) && cbor_value_is_array(&svcMap))
             {
                 int i = 0;
                 CborValue owners = { .parser = NULL };
@@ -258,7 +258,7 @@ OCStackResult CBORPayloadToSVC(const uint8_t *cborPayload, size_t size,
                 svc->owners = (OicUuid_t *)OICCalloc(svc->ownersLen, sizeof(*svc->owners));
                 VERIFY_NON_NULL(TAG, svc->owners, ERROR);
 
-                while (cbor_value_is_valid(&owners))
+                while (cbor_value_is_valid(&owners) && cbor_value_is_byte_string(&owners))
                 {
                     uint8_t *owner = NULL;
                     cborFindResult = cbor_value_dup_byte_string(&owners, &owner, &len, NULL);
@@ -414,7 +414,7 @@ static OCStackResult CreateSVCResource()
 {
     OCStackResult ret = OCCreateResource(&gSvcHandle,
                                          OIC_RSRC_TYPE_SEC_SVC,
-                                         OIC_MI_DEF,
+                                         OC_RSRVD_INTERFACE_DEFAULT,
                                          OIC_RSRC_SVC_URI,
                                          SVCEntityHandler,
                                          NULL,
index 0bd3f75..96afacc 100644 (file)
@@ -281,7 +281,7 @@ OCStackResult CreateVerResource()
 {
     OCStackResult ret = OCCreateResource(&gVerHandle,
                                          OIC_RSRC_TYPE_SEC_VER,
-                                         OIC_MI_DEF,
+                                         OC_RSRVD_INTERFACE_DEFAULT,
                                          OIC_RSRC_VER_URI,
                                          VerEntityHandler,
                                          NULL,
index 09191cb..0f41aab 100644 (file)
@@ -20,6 +20,7 @@
 
 #include <stdlib.h>
 #include <string.h>
+#include "utlist.h"
 #include "cJSON.h"
 #include "base64.h"
 #include "cainterface.h"
@@ -201,11 +202,12 @@ static void ConvertJsonToCBOR(const char *jsonFileName, const char *cborFileName
     value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
     //printf("CRED json : \n%s\n", cJSON_PrintUnformatted(value));
     size_t credCborSize = 0;
+    int secureFlag = 0;
     if (NULL != value)
     {
         OicSecCred_t *cred = JSONToCredBin(jsonStr);
         VERIFY_NON_NULL(TAG, cred, FATAL);
-        ret = CredToCBORPayload(cred, &credCbor, &credCborSize);
+        ret = CredToCBORPayload(cred, &credCbor, &credCborSize, secureFlag);
         if(OC_STACK_OK != ret)
         {
             OIC_LOG (ERROR, TAG, "Failed converting Cred to Cbor Payload");
@@ -342,23 +344,9 @@ OicSecAcl_t* JSONToAclBin(const char * jsonStr)
             cJSON *jsonAcl = cJSON_GetArrayItem(jsonAclArray, idx);
             VERIFY_NON_NULL(TAG, jsonAcl, ERROR);
 
-            OicSecAcl_t *acl = NULL;
-            if(idx == 0)
-            {
-                acl = headAcl;
-            }
-            else
-            {
-                acl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
-                OicSecAcl_t *temp = headAcl;
-                while (temp->next)
-                {
-                    temp = temp->next;
-                }
-                temp->next = acl;
-            }
-
-            VERIFY_NON_NULL(TAG, acl, ERROR);
+            OicSecAce_t *ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+            VERIFY_NON_NULL(TAG, ace, ERROR);
+            LL_APPEND(headAcl->aces, ace);
 
             size_t jsonObjLen = 0;
             cJSON *jsonObj = NULL;
@@ -367,11 +355,11 @@ OicSecAcl_t* JSONToAclBin(const char * jsonStr)
             VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
             if(strcmp(jsonObj->valuestring, WILDCARD_RESOURCE_URI) == 0)
             {
-                acl->subject.id[0] = '*';
+                ace->subjectuuid.id[0] = '*';
             }
             else
             {
-                ret = ConvertStrToUuid(jsonObj->valuestring, &acl->subject);
+                ret = ConvertStrToUuid(jsonObj->valuestring, &ace->subjectuuid);
                 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
             }
             // Resources -- Mandatory
@@ -379,87 +367,134 @@ OicSecAcl_t* JSONToAclBin(const char * jsonStr)
             VERIFY_NON_NULL(TAG, jsonObj, ERROR);
             VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
 
-            acl->resourcesLen = (size_t)cJSON_GetArraySize(jsonObj);
-
-            VERIFY_SUCCESS(TAG, acl->resourcesLen > 0, ERROR);
-            acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
-            VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
+            size_t resourcesLen = (size_t)cJSON_GetArraySize(jsonObj);
+            VERIFY_SUCCESS(TAG, resourcesLen > 0, ERROR);
 
-            size_t idxx = 0;
-            do
+            for(size_t idxx = 0; idxx < resourcesLen; idxx++)
             {
+                OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+                VERIFY_NON_NULL(TAG, rsrc, ERROR);
+
                 cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx);
                 VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);
 
+                //href
                 size_t jsonRsrcObjLen = 0;
                 cJSON *jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_HREF_NAME);
                 VERIFY_NON_NULL(TAG, jsonRsrcObj, ERROR);
                 VERIFY_SUCCESS(TAG, cJSON_String == jsonRsrcObj->type, ERROR);
 
                 jsonRsrcObjLen = strlen(jsonRsrcObj->valuestring) + 1;
-                acl->resources[idxx] = (char*)OICMalloc(jsonRsrcObjLen);
+                rsrc->href = (char*)OICMalloc(jsonRsrcObjLen);
+                VERIFY_NON_NULL(TAG, (rsrc->href), ERROR);
+                OICStrcpy(rsrc->href, jsonRsrcObjLen, jsonRsrcObj->valuestring);
+
+                //rel
+                jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_REL_NAME);
+                if(jsonRsrcObj)
+                {
+                    jsonRsrcObjLen = strlen(jsonRsrcObj->valuestring) + 1;
+                    rsrc->rel = (char*)OICMalloc(jsonRsrcObjLen);
+                    VERIFY_NON_NULL(TAG, (rsrc->rel), ERROR);
+                    OICStrcpy(rsrc->rel, jsonRsrcObjLen, jsonRsrcObj->valuestring);
+                }
 
-                VERIFY_NON_NULL(TAG, (acl->resources[idxx]), ERROR);
-                OICStrcpy(acl->resources[idxx], jsonRsrcObjLen, jsonRsrcObj->valuestring);
+                //rt
+                jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_RT_NAME);
+                if(jsonRsrcObj && cJSON_Array == jsonRsrcObj->type)
+                {
+                    rsrc->typeLen = (size_t)cJSON_GetArraySize(jsonRsrcObj);
+                    VERIFY_SUCCESS(TAG, (0 < rsrc->typeLen), ERROR);
+                    rsrc->types = (char**)OICCalloc(rsrc->typeLen, sizeof(char*));
+                    VERIFY_NON_NULL(TAG, (rsrc->types), ERROR);
+                    for(size_t i = 0; i < rsrc->typeLen; i++)
+                    {
+                        cJSON *jsonRsrcType = cJSON_GetArrayItem(jsonRsrcObj, i);
+                        rsrc->types[i] = OICStrdup(jsonRsrcType->valuestring);
+                        VERIFY_NON_NULL(TAG, (rsrc->types[i]), ERROR);
+                    }
+                }
+
+                //if
+                jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_IF_NAME);
+                if(jsonRsrcObj && cJSON_Array == jsonRsrcObj->type)
+                {
+                    rsrc->interfaceLen = (size_t)cJSON_GetArraySize(jsonRsrcObj);
+                    VERIFY_SUCCESS(TAG, (0 < rsrc->interfaceLen), ERROR);
+                    rsrc->interfaces = (char**)OICCalloc(rsrc->interfaceLen, sizeof(char*));
+                    VERIFY_NON_NULL(TAG, (rsrc->interfaces), ERROR);
+                    for(size_t i = 0; i < rsrc->interfaceLen; i++)
+                    {
+                        cJSON *jsonInterface = cJSON_GetArrayItem(jsonRsrcObj, i);
+                        rsrc->interfaces[i] = OICStrdup(jsonInterface->valuestring);
+                        VERIFY_NON_NULL(TAG, (rsrc->interfaces[i]), ERROR);
+                    }
+                }
 
-            } while ( ++idxx < acl->resourcesLen);
+                LL_APPEND(ace->resources, rsrc);
+            }
 
             // Permissions -- Mandatory
             jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_PERMISSION_NAME);
             VERIFY_NON_NULL(TAG, jsonObj, ERROR);
             VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-            acl->permission = jsonObj->valueint;
-            //Period -- Not Mandatory
-            cJSON *jsonPeriodObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_PERIOD_NAME);
-            if(jsonPeriodObj)
+            ace->permission = jsonObj->valueint;
+
+            //Validity -- Not Mandatory
+            cJSON *jsonValidityObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_VALIDITY_NAME);
+            if(jsonValidityObj)
             {
-                VERIFY_SUCCESS(TAG, cJSON_Array == jsonPeriodObj->type, ERROR);
-                acl->prdRecrLen = (size_t)cJSON_GetArraySize(jsonPeriodObj);
-                if(acl->prdRecrLen > 0)
+                VERIFY_SUCCESS(TAG, cJSON_Array == jsonValidityObj->type, ERROR);
+                size_t validityLen = cJSON_GetArraySize(jsonValidityObj);
+                VERIFY_SUCCESS(TAG, (0 < validityLen), ERROR);
+
+                cJSON *jsonValidity = NULL;
+                for(size_t i = 0; i < validityLen; i++)
                 {
-                    acl->periods = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
-                    VERIFY_NON_NULL(TAG, acl->periods, ERROR);
+                    jsonValidity = cJSON_GetArrayItem(jsonValidityObj, i);
+                    VERIFY_NON_NULL(TAG, jsonValidity, ERROR);
+                    VERIFY_SUCCESS(TAG, (jsonValidity->type == cJSON_Array), ERROR);
+
+                    OicSecValidity_t* validity = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+                    VERIFY_NON_NULL(TAG, validity, ERROR);
+                    LL_APPEND(ace->validities, validity);
 
-                    cJSON *jsonPeriod = NULL;
-                    for(size_t i = 0; i < acl->prdRecrLen; i++)
+                    //Period
+                    cJSON* jsonPeriod = cJSON_GetArrayItem(jsonValidity, 0);
+                    if(jsonPeriod)
                     {
-                        jsonPeriod = cJSON_GetArrayItem(jsonPeriodObj, i);
-                        VERIFY_NON_NULL(TAG, jsonPeriod, ERROR);
+                        VERIFY_SUCCESS(TAG, (cJSON_String == jsonPeriod->type), ERROR);
 
                         jsonObjLen = strlen(jsonPeriod->valuestring) + 1;
-                        acl->periods[i] = (char*)OICMalloc(jsonObjLen);
-                        VERIFY_NON_NULL(TAG, acl->periods[i], ERROR);
-                        OICStrcpy(acl->periods[i], jsonObjLen, jsonPeriod->valuestring);
+                        validity->period = (char*)OICMalloc(jsonObjLen);
+                        VERIFY_NON_NULL(TAG, validity->period, ERROR);
+                        OICStrcpy(validity->period, jsonObjLen, jsonPeriod->valuestring);
                     }
-                }
-            }
-            //Recurrence -- Not mandatory
-            cJSON *jsonRecurObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_RECURRENCES_NAME);
-            if(jsonRecurObj)
-            {
-
-                VERIFY_SUCCESS(TAG, cJSON_Array == jsonRecurObj->type, ERROR);
 
-                if(acl->prdRecrLen > 0)
-                {
-                    acl->recurrences = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
-                    VERIFY_NON_NULL(TAG, acl->recurrences, ERROR);
-
-                    cJSON *jsonRecur = NULL;
-                    for(size_t i = 0; i < acl->prdRecrLen; i++)
+                    //Recurrence
+                    cJSON* jsonRecurObj = cJSON_GetArrayItem(jsonValidity, 1);
+                    if(jsonRecurObj)
                     {
-                        jsonRecur = cJSON_GetArrayItem(jsonRecurObj, i);
-                        VERIFY_NON_NULL(TAG, jsonRecur, ERROR);
-                        jsonObjLen = strlen(jsonRecur->valuestring) + 1;
-                        acl->recurrences[i] = (char*)OICMalloc(jsonObjLen);
-                        VERIFY_NON_NULL(TAG, acl->recurrences[i], ERROR);
-                        OICStrcpy(acl->recurrences[i], jsonObjLen, jsonRecur->valuestring);
+                        VERIFY_SUCCESS(TAG, (cJSON_Array == jsonRecurObj->type), ERROR);
+                        validity->recurrenceLen = cJSON_GetArraySize(jsonRecurObj);
+                        VERIFY_SUCCESS(TAG, (0 < validity->recurrenceLen), ERROR);
+
+                        validity->recurrences = (char**)OICCalloc(validity->recurrenceLen, sizeof(char*));
+                        VERIFY_NON_NULL(TAG, validity->recurrences, ERROR);
+
+                        cJSON *jsonRecur = NULL;
+                        for(size_t i = 0; i < validity->recurrenceLen; i++)
+                        {
+                            jsonRecur = cJSON_GetArrayItem(jsonRecurObj, i);
+                            VERIFY_NON_NULL(TAG, jsonRecur, ERROR);
+                            jsonObjLen = strlen(jsonRecur->valuestring) + 1;
+                            validity->recurrences[i] = (char*)OICMalloc(jsonObjLen);
+                            VERIFY_NON_NULL(TAG, validity->recurrences[i], ERROR);
+                            OICStrcpy(validity->recurrences[i], jsonObjLen, jsonRecur->valuestring);
+                        }
                     }
                 }
             }
-
-            acl->next = NULL;
-
         } while( ++idx < numAcl);
     }
 
@@ -733,7 +768,6 @@ OicSecCred_t * JSONToCredBin(const char * jsonStr)
         int numCred = cJSON_GetArraySize(jsonCredArray);
         VERIFY_SUCCESS(TAG, numCred > 0, ERROR);
         int idx = 0;
-        size_t ownersLen = 0;
         do
         {
             cJSON *jsonCred = cJSON_GetArrayItem(jsonCredArray, idx);
@@ -791,6 +825,24 @@ OicSecCred_t * JSONToCredBin(const char * jsonStr)
                 VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
                 memcpy(cred->privateData.data, jsonPriv->valuestring, jsonObjLen);
                 cred->privateData.len = jsonObjLen;
+
+                cJSON *jsonEncoding = cJSON_GetObjectItem(jsonObj, OIC_JSON_ENCODING_NAME);
+                VERIFY_NON_NULL(TAG, jsonEncoding, ERROR);
+
+                if(strcmp(OIC_SEC_ENCODING_RAW, jsonEncoding->valuestring) == 0)
+                {
+                    cred->privateData.encoding = OIC_ENCODING_RAW;
+                }
+                else if(strcmp(OIC_SEC_ENCODING_BASE64, jsonEncoding->valuestring) == 0)
+                {
+                    cred->privateData.encoding = OIC_ENCODING_BASE64;
+                }
+                else
+                {
+                    printf("Unknow encoding type dectected!\n");
+                    printf("json2cbor will use \"oic.sec.encoding.raw\" as default encoding type.\n");
+                    cred->privateData.encoding = OIC_ENCODING_RAW;
+                }
             }
 #ifdef __WITH_X509__
             //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type.
index c431d77..0018e5e 100644 (file)
@@ -25,27 +25,25 @@ import os.path
 srmtest_env = env.Clone()
 
 src_dir = srmtest_env.get('SRC_DIR')
+target_os = env.get('TARGET_OS')
 
 ######################################################################
 # Build flags
 ######################################################################
 srmtest_env.PrependUnique(CPPPATH = [
-        '../../ocmalloc/include',
+               '../../../c_common/oic_malloc/include',
                '../../connectivity/inc',
                '../../connectivity/api',
                '../../connectivity/external/inc',
                '../../connectivity/lib/libcoap-4.1.1',
-               '../include',
                '../include/internal',
                '../../logger/include',
-               '../../ocmalloc/include',
                '../../stack/include',
                '../../stack/include/internal',
                '../../../oc_logger/include',
                '../../../../extlibs/gtest/gtest-1.7.0/include',
                '../../../../extlibs/cjson/',
-                '../provisioning/include',
-#              '../../../../extlibs/tinydtls/',
+               '../provisioning/include',
                '../include'
                ])
 
@@ -62,11 +60,18 @@ srmtest_env.PrependUnique(LIBS = ['ocsrm',
                                     'gtest_main'])
 
 if env.get('SECURED') == '1':
-    srmtest_env.AppendUnique(LIBS = ['tinydtls'])
+    srmtest_env.AppendUnique(LIBS = ['tinydtls', 'timer'])
 
-if not env.get('RELEASE'):
+if 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.
+       srmtest_env.AppendUnique(CPPDEFINES = ['HAVE_LOCALTIME_R'])
+
 ######################################################################
 # Source files and Targets
 ######################################################################
@@ -82,14 +87,15 @@ unittest = srmtest_env.Program('unittest', ['aclresourcetest.cpp',
                                             'base64tests.cpp',
                                             'svcresourcetest.cpp',
                                             'srmtestcommon.cpp',
-                                            'directpairingtest.cpp'])
+                                            'directpairingtest.cpp',
+                                            'crlresourcetest.cpp'])
 
 Alias("test", [unittest])
 
 unittest_src_dir = src_dir + '/resource/csdk/security/unittest/'
-unittest_build_dir = env.get('BUILD_DIR') + 'resource/csdk/security/unittest'
+unittest_build_dir = os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk', 'security', 'unittest') + os.sep
 
-srmtest_env.AppendUnique(CPPDEFINES = ['SECURITY_BUILD_UNITTEST_DIR='+unittest_build_dir])
+srmtest_env.AppendUnique(CPPDEFINES = ['SECURITY_BUILD_UNITTEST_DIR='+unittest_build_dir.encode('string_escape')])
 
 srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
     unittest_src_dir + 'oic_unittest.json'))
@@ -97,6 +103,8 @@ srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
     unittest_src_dir + 'oic_unittest_acl1.json'))
 srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
     unittest_src_dir + 'oic_unittest_default_acl.json'))
+srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
+    unittest_src_dir + 'oic_svr_db.json'))
 
 srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
     unittest_src_dir + 'oic_unittest.dat'))
@@ -104,17 +112,22 @@ srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
     unittest_src_dir + 'oic_unittest_acl1.dat'))
 srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
     unittest_src_dir + 'oic_unittest_default_acl.dat'))
-
+srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
+    unittest_src_dir + 'oic_svr_db_prov.dat'))
+srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
+    unittest_src_dir + 'oic_svr_db.dat'))
+    
 env.AppendTarget('test')
 if env.get('TEST') == '1':
        target_os = env.get('TARGET_OS')
-       if target_os == 'linux':
+       if target_os in ['linux', 'windows']:
                out_dir = env.get('BUILD_DIR')
                result_dir = env.get('BUILD_DIR') + '/test_out/'
                if not os.path.isdir(result_dir):
                        os.makedirs(result_dir)
                srmtest_env.AppendENVPath('GTEST_OUTPUT', ['xml:'+ result_dir])
                srmtest_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir])
+               srmtest_env.AppendENVPath('PATH', [os.path.join(out_dir, 'resource', 'csdk')])
                srmtest_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
                ut = srmtest_env.Command ('ut', None, out_dir + '/resource/csdk/security/unittest/unittest')
                AlwaysBuild ('ut')
index 558406a..dbf4cb8 100644 (file)
@@ -19,9 +19,7 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
-#include <pwd.h>
-#include <grp.h>
-#include <linux/limits.h>
+#include "utlist.h"
 #include <sys/stat.h>
 #include "ocstack.h"
 #include "psinterface.h"
@@ -47,47 +45,116 @@ using namespace std;
 #define TAG  "SRM-ACL-UT"
 
 // These paths match jenkins build configuration.
-const char* DEFAULT_ACL_FILE_NAME = "/oic_unittest_default_acl.dat";
-const char* ACL1_FILE_NAME = "/oic_unittest_acl1.dat";
+const char* DEFAULT_ACL_FILE_NAME = "oic_unittest_default_acl.dat";
+const char* ACL1_FILE_NAME = "oic_unittest_acl1.dat";
 
 #define NUM_ACE_FOR_WILDCARD_IN_ACL1_DAT (1)
 
-TEST(ACLResourceTest, CBORDefaultACLConversion)
+static bool AddResourceToACE(OicSecAce_t* ace, const char* rsrcName,
+                             const char* typeName, const char* interfaceName)
 {
-    OicSecAcl_t *defaultAcl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
-    ASSERT_TRUE(defaultAcl != NULL);
-    uint8_t defaultAclSub[] = { 0x2a };
-    memcpy(defaultAcl->subject.id, defaultAclSub, sizeof(defaultAclSub));
-    defaultAcl->permission = 2;
-    const char *defaulAclRsrc[] = { "/oic/res", "/oic/d", "/oic/p", "/oic/res/types/d",
-            "/oic/ad", "/oic/sec/acl", "/oic/sec/doxm", "/oic/sec/pstat"};
-    defaultAcl->resourcesLen = 8;
-    defaultAcl->resources = (char **)OICCalloc(defaultAcl->resourcesLen, sizeof(char *));
-    ASSERT_TRUE(defaultAcl->resources != NULL);
-    for (size_t i = 0 ; i < defaultAcl->resourcesLen; i++)
+    OicSecRsrc_t* rsrc = NULL;
+
+    VERIFY_NON_NULL(TAG, ace, ERROR);
+    VERIFY_NON_NULL(TAG, rsrcName, ERROR);
+    VERIFY_NON_NULL(TAG, interfaceName, ERROR);
+    VERIFY_NON_NULL(TAG, typeName, ERROR);
+
+    rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+    VERIFY_NON_NULL(TAG, rsrc, ERROR);
+    rsrc->href = OICStrdup(rsrcName);
+    VERIFY_NON_NULL(TAG, rsrc->href, ERROR);
+
+    rsrc->typeLen = 1;
+    rsrc->types = (char**)OICCalloc(1, sizeof(char*));
+    VERIFY_NON_NULL(TAG, rsrc->types, ERROR);
+    rsrc->types[0] = OICStrdup(typeName);
+    VERIFY_NON_NULL(TAG, rsrc->types[0], ERROR);
+
+    rsrc->interfaceLen = 1;
+    rsrc->interfaces = (char**)OICCalloc(1, sizeof(char*));
+    VERIFY_NON_NULL(TAG, rsrc->interfaces, ERROR);
+    rsrc->interfaces[0] = OICStrdup(interfaceName);
+    VERIFY_NON_NULL(TAG, rsrc->interfaces[0], ERROR);
+
+    LL_APPEND(ace->resources, rsrc);
+    return true;
+exit:
+    if(rsrc)
+    {
+        if(rsrc->href)
+        {
+            OICFree(rsrc->href);
+            OICFree(rsrc->types[0]);
+            OICFree(rsrc->types);
+            OICFree(rsrc->interfaces[0]);
+            OICFree(rsrc->interfaces);
+        }
+        OICFree(rsrc);
+    }
+    return false;
+}
+
+static int GetNumberOfResource(const OicSecAce_t* ace)
+{
+    int ret = 0;
+    OicSecRsrc_t* rsrc = NULL;
+    LL_FOREACH(ace->resources, rsrc)
     {
-        defaultAcl->resources[i] = OICStrdup(defaulAclRsrc[i]);
-        ASSERT_TRUE(defaultAcl->resources[i] != NULL);
+        ret++;
     }
+
+    return ret;
+}
+
+TEST(ACLResourceTest, CBORDefaultACLConversion)
+{
+    uint8_t defaultAclSub[] = { 0x2a };
     uint8_t defaultAclOwnrs[] = {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
         0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32};
+
+    OicSecAcl_t *defaultAcl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_TRUE(NULL != defaultAcl);
+    OicSecAce_t *ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+    ASSERT_TRUE(NULL != ace);
+    ace->permission = 2;
+    memcpy(ace->subjectuuid.id, defaultAclSub, sizeof(defaultAclSub));
+    LL_APPEND(defaultAcl->aces, ace);
+
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/res", "oic.wk.res", "oic.if.ll"));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/d", "oic.wk.d", "oic.if.r"));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/p", "oic.wk.p", "oic.if.r"));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/res/types/d", "oic.wk.unknow", "oic.if.r"));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/ad", "oic.wk.ad", "oic.if.baseline"));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/sec/acl", "oic.r.acl", "oic.if.baseline"));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/sec/doxm", "oic.r.doxm" ,"oic.if.baseline"));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/sec/pstat", "oic.r.pstat" ,"oic.if.baseline"));
+
     memcpy(defaultAcl->rownerID.id, defaultAclOwnrs, sizeof(defaultAclOwnrs));
 
     size_t defaultAclSize = 0;
     uint8_t *defaultPsStorage = NULL;
     OCStackResult convRet = AclToCBORPayload(defaultAcl, &defaultPsStorage, &defaultAclSize);
     EXPECT_EQ(OC_STACK_OK, convRet);
-    ASSERT_TRUE(defaultPsStorage != NULL);
+    ASSERT_TRUE(NULL != defaultPsStorage);
     EXPECT_NE(0, defaultAclSize);
 
     OicSecAcl_t* convertedAcl = CBORPayloadToAcl(defaultPsStorage, defaultAclSize);
-    ASSERT_TRUE(convertedAcl != NULL);
+    ASSERT_TRUE(NULL != convertedAcl);
 
-    EXPECT_EQ(defaultAcl->resourcesLen, convertedAcl->resourcesLen);
-    for(int i = 0; i < convertedAcl->resourcesLen; i++)
+    size_t rsrcCnt1 = 0;
+    size_t rsrcCnt2 = 0;
+    OicSecAce_t* tempAce = NULL;
+    LL_FOREACH(defaultAcl->aces, tempAce)
+    {
+        rsrcCnt1 += GetNumberOfResource(tempAce);
+    }
+    tempAce = NULL;
+    LL_FOREACH(convertedAcl->aces, tempAce)
     {
-        EXPECT_EQ(0, strcmp(defaultAcl->resources[i], convertedAcl->resources[i]));
+        rsrcCnt2 += GetNumberOfResource(tempAce);
     }
+    EXPECT_EQ(rsrcCnt1, rsrcCnt2);
 
     DeleteACLList(convertedAcl);
     DeleteACLList(defaultAcl);
@@ -96,79 +163,47 @@ TEST(ACLResourceTest, CBORDefaultACLConversion)
 
 TEST(ACLResourceTest, CBORACLConversion)
 {
+    uint8_t ownrs[] = {0x32, 0x32, 0x32, 0x32,
+                       0x32, 0x32, 0x32, 0x32,
+                       0x32, 0x32, 0x32, 0x32,
+                       0x32, 0x32, 0x32, 0x32};
+    const char* subjectUuid[3] = {"0000000000000000",
+                                  "1111111111111111",
+                                  "2222222222222222"};
+    const uint16_t permission[3] = {2, 6, 31};
+    const size_t numOfRsrc[3] = {6, 2, 2};
+
     OicSecAcl_t *secAcl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
     ASSERT_TRUE(secAcl != NULL);
-    uint8_t subjectBytes[] = { 0x2a };
-    memcpy(secAcl->subject.id, subjectBytes, sizeof(subjectBytes));
-    secAcl->permission = 2;
-    const char *rsrc[] = { "/oic/res", "/oic/d", "/oic/p", "/oic/res/types/d",
-                           "/oic/ad", "/oic/sec/acl"};
-    secAcl->resourcesLen = 6;
-    secAcl->resources = (char **)OICCalloc(secAcl->resourcesLen, sizeof(char *));
-    ASSERT_TRUE(secAcl->resources != NULL);
-    for (size_t i = 0 ; i < secAcl->resourcesLen; i++)
-    {
-        secAcl->resources[i] = OICStrdup(rsrc[i]);
-        ASSERT_TRUE(secAcl->resources[i] != NULL);
-
-    }
-
-    uint8_t ownrs[] = {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
-        0x32, 0x32, 0x32, 0x32, 0x32, 0x32};
     memcpy(secAcl->rownerID.id, ownrs, sizeof(ownrs));
 
-    OicSecAcl_t *secAcl1 = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
-    ASSERT_TRUE(secAcl1 != NULL);
-    memcpy(secAcl1->subject.id, subjectBytes, sizeof(subjectBytes));
-    secAcl1->permission = 6;
-    const char *rsrc1[] = { "/oic/sec/doxm", "/oic/sec/pstat"};
-    secAcl1->resourcesLen = 2;
-    secAcl1->resources = (char **)OICCalloc(secAcl1->resourcesLen, sizeof(char *));
-    ASSERT_TRUE(secAcl1->resources != NULL);
-    for (size_t i = 0 ; i < secAcl1->resourcesLen; i++)
-    {
-        secAcl1->resources[i] = OICStrdup(rsrc1[i]);
-        ASSERT_TRUE(secAcl1->resources[i] != NULL);
-    }
-    memcpy(secAcl1->rownerID.id, ownrs, sizeof(ownrs));
-    secAcl->next = secAcl1;
-
-    OicSecAcl_t *secAcl2 = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
-    ASSERT_TRUE(secAcl2 != NULL);
-    uint8_t subjectBytes1[] = {0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
-        0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31};
-    memcpy(secAcl2->subject.id, subjectBytes1, sizeof(subjectBytes1));
-    secAcl2->permission = 255;
-    const char *rsrc2[] = {"/oic/light", "/oic/fan" };
-    secAcl2->resourcesLen = 2;
-    secAcl2->resources = (char **)OICCalloc(secAcl2->resourcesLen, sizeof(char *));
-    ASSERT_TRUE(secAcl2->resources != NULL);
-    for (size_t i = 0 ; i < secAcl2->resourcesLen; i++)
-    {
-        secAcl2->resources[i] = OICStrdup(rsrc2[i]);
-        ASSERT_TRUE(secAcl2->resources[i] != NULL);
-    }
-    memcpy(secAcl2->rownerID.id, ownrs, sizeof(ownrs));
-    secAcl1->next = secAcl2;
-
-    OicSecAcl_t *secAcl3 = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
-    ASSERT_TRUE(secAcl3 != NULL);
-    uint8_t subjectBytes2[] = {0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33,
-                               0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33};
-    memcpy(secAcl3->subject.id, subjectBytes2, sizeof(subjectBytes2));
-    secAcl3->permission = 255;
-    const char *rsrc3[] = {"/oic/light", "/oic/garage" };
-    secAcl3->resourcesLen = 2;
-    secAcl3->resources = (char **)OICCalloc(secAcl3->resourcesLen, sizeof(char *));
-    ASSERT_TRUE(secAcl3->resources != NULL);
-    for (size_t i = 0 ; i < secAcl3->resourcesLen; i++)
-    {
-        secAcl3->resources[i] = OICStrdup(rsrc3[i]);
-        ASSERT_TRUE(secAcl3->resources[i] != NULL);
-    }
-    memcpy(secAcl3->rownerID.id, ownrs, sizeof(ownrs));
-    secAcl2->next = secAcl3;
-    secAcl3->next = NULL;
+    OicSecAce_t *ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+    ASSERT_TRUE(NULL != ace);
+    ace->permission = permission[0];
+    memcpy(ace->subjectuuid.id, subjectUuid[0], strlen(subjectUuid[0]));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/res", "oic.wk.res", "oic.if.ll"));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/d", "oic.wk.d", "oic.if.r"));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/p", "oic.wk.p", "oic.if.r"));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/res/types/d", "oic.wk.unknow", "oic.if.r"));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/ad", "oic.wk.ad", "oic.if.baseline"));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/oic/sec/acl", "oic.r.acl", "oic.if.baseline"));
+    LL_APPEND(secAcl->aces, ace);
+
+    OicSecAce_t *ace1 = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+    ASSERT_TRUE(NULL != ace1);
+    ace1->permission = permission[1];
+    memcpy(ace1->subjectuuid.id, subjectUuid[1], strlen(subjectUuid[1]));
+    EXPECT_EQ(true, AddResourceToACE(ace1, "/oic/sec/doxm", "oic.r.doxm" ,"oic.if.baseline"));
+    EXPECT_EQ(true, AddResourceToACE(ace1, "/oic/sec/pstat", "oic.r.pstat" ,"oic.if.baseline"));
+    LL_APPEND(secAcl->aces, ace1);
+
+    OicSecAce_t *ace2 = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+    ASSERT_TRUE(NULL != ace2);
+    ace2->permission = permission[2];
+    memcpy(ace2->subjectuuid.id, subjectUuid[2], strlen(subjectUuid[2]));
+    EXPECT_EQ(true, AddResourceToACE(ace2, "/oic/light", "oic.core", "oic.if.baseline"));
+    EXPECT_EQ(true, AddResourceToACE(ace2, "/oic/garage", "oic.core", "oic.if.baseline"));
+    LL_APPEND(secAcl->aces, ace2);
 
     size_t size = 0;
     uint8_t *psStorage = NULL;
@@ -176,12 +211,35 @@ TEST(ACLResourceTest, CBORACLConversion)
     ASSERT_TRUE(NULL != psStorage);
     OicSecAcl_t *acl = CBORPayloadToAcl(psStorage, size);
     ASSERT_TRUE(NULL != acl);
-    EXPECT_EQ(2, acl->permission);
-    EXPECT_EQ(6 , acl->resourcesLen);
-    EXPECT_STREQ("/oic/res", acl->resources[0]);
+
+    size_t numberOfCheckedAce = 0;
+    OicSecAce_t* tempAce = NULL;
+    LL_FOREACH(acl->aces, tempAce)
+    {
+        if(memcmp(tempAce->subjectuuid.id, subjectUuid[0], strlen(subjectUuid[0])) == 0)
+        {
+            EXPECT_EQ(numOfRsrc[0], GetNumberOfResource(tempAce));
+            EXPECT_EQ(permission[0], tempAce->permission);
+            numberOfCheckedAce++;
+        }
+        if(memcmp(tempAce->subjectuuid.id, subjectUuid[1], strlen(subjectUuid[1])) == 0)
+        {
+            EXPECT_EQ(numOfRsrc[1], GetNumberOfResource(tempAce));
+            EXPECT_EQ(permission[1], tempAce->permission);
+            numberOfCheckedAce++;
+        }
+        if(memcmp(tempAce->subjectuuid.id, subjectUuid[2], strlen(subjectUuid[2])) == 0)
+        {
+            EXPECT_EQ(numOfRsrc[2], GetNumberOfResource(tempAce));
+            EXPECT_EQ(permission[2], tempAce->permission);
+            numberOfCheckedAce++;
+        }
+    }
+    EXPECT_EQ(3, numberOfCheckedAce);
+
     DeleteACLList(acl);
-    OICFree(psStorage);
     DeleteACLList(secAcl);
+    OICFree(psStorage);
 }
 
 //InitResource Tests
@@ -198,27 +256,29 @@ TEST(ACLResourceTest, GetDefaultACLTests)
     size_t size = 0;
 
     ASSERT_TRUE(ReadCBORFile(DEFAULT_ACL_FILE_NAME, OIC_JSON_ACL_NAME, &payload, &size));
-    ASSERT_TRUE(payload != NULL);
+    ASSERT_TRUE(NULL != payload);
 
     OicSecAcl_t *psAcl = CBORPayloadToAcl(payload, size);
-    ASSERT_TRUE(psAcl != NULL);
+    ASSERT_TRUE(NULL != psAcl);
 
     OicSecAcl_t *acl = NULL;
     EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&acl));
-    ASSERT_TRUE(acl != NULL);
+    ASSERT_TRUE(NULL != acl);
 
     // Verify if the SRM generated default ACL matches with unit test default
     if (acl && psAcl)
     {
-        EXPECT_TRUE(strcmp((char*)acl->subject.id, (char*)psAcl->subject.id) == 0);
-        EXPECT_EQ(acl->resourcesLen, psAcl->resourcesLen);
-        for (size_t i = 0; i < acl->resourcesLen; i++)
+        OicSecAce_t* tempAce1 = NULL;
+        OicSecAce_t* tempAce2 = NULL;
+
+        for(tempAce1 = acl->aces, tempAce2 = psAcl->aces;
+            tempAce1 && tempAce2; tempAce1 = tempAce1->next,
+            tempAce2 = tempAce2->next)
         {
-            EXPECT_EQ(strlen(acl->resources[i]), strlen(psAcl->resources[i]));
-            EXPECT_TRUE(memcmp(acl->resources[i], psAcl->resources[i],
-                            strlen(acl->resources[i])) == 0);
+            EXPECT_TRUE(memcmp(tempAce1->subjectuuid.id, tempAce2->subjectuuid.id, sizeof(tempAce1->subjectuuid.id)) == 0);
+            EXPECT_EQ(tempAce1->permission, tempAce2->permission);
+            EXPECT_EQ(GetNumberOfResource(tempAce1), GetNumberOfResource(tempAce2));
         }
-        EXPECT_EQ(acl->permission, psAcl->permission);
     }
 
     DeleteACLList(psAcl);
@@ -234,15 +294,20 @@ TEST(ACLResourceTest, ACLPostTest)
     uint8_t *payload = NULL;
     size_t size = 0;
 
+    static OCPersistentStorage ps = OCPersistentStorage();
+    SetPersistentHandler(&ps, true);
+
+    OicSecAcl_t *defaultAcl = NULL;
+    EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&defaultAcl));
+    ASSERT_TRUE(defaultAcl != NULL);
+    EXPECT_EQ(OC_STACK_OK, SetDefaultACL(defaultAcl));
+
     ASSERT_TRUE(ReadCBORFile(ACL1_FILE_NAME, OIC_JSON_ACL_NAME, &payload, &size));
     ASSERT_TRUE(NULL != payload);
 
     OCSecurityPayload *securityPayload = OCSecurityPayloadCreate(payload, size);
     ASSERT_TRUE(NULL != securityPayload);
 
-    static OCPersistentStorage ps = OCPersistentStorage();
-    SetPersistentHandler(&ps, true);
-
     // Create Entity Handler POST request payload
     OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
     ehReq.method = OC_REST_POST;
@@ -254,8 +319,8 @@ TEST(ACLResourceTest, ACLPostTest)
     ASSERT_TRUE(NULL != acl);
 
     // Verify if SRM contains ACL for the subject
-    OicSecAcl_t *savePtr = NULL;
-    const OicSecAcl_t* subjectAcl = GetACLResourceData(&(acl->subject), &savePtr);
+    OicSecAce_t *savePtr = NULL;
+    const OicSecAce_t* subjectAcl = GetACLResourceData(&(acl->aces->subjectuuid), &savePtr);
     ASSERT_TRUE(NULL != subjectAcl);
 
     // Perform cleanup
@@ -265,6 +330,11 @@ TEST(ACLResourceTest, ACLPostTest)
     DeleteACLList(acl);
 }
 
+extern "C" {
+    // gAcl is a pointer to the the global ACL used by SRM
+    extern OicSecAcl_t  *gAcl;
+}
+
 // GetACLResource tests
 TEST(ACLResourceTest, GetACLResourceTests)
 {
@@ -287,16 +357,16 @@ TEST(ACLResourceTest, GetACLResourceTests)
     EXPECT_EQ(OC_STACK_OK, SetDefaultACL(acl1));
 
     // Verify that ACL file contains 2 ACE entries for 'WILDCARD' subject
-    const OicSecAcl_t *acl = NULL;
-    OicSecAcl_t *savePtr = NULL;
+    const OicSecAce_t *ace = NULL;
+    OicSecAce_t *savePtr = NULL;
     OicUuid_t subject = WILDCARD_SUBJECT_ID;
     int count = 0;
 
     do
     {
-        acl = GetACLResourceData(&subject, &savePtr);
-        count = (NULL != acl) ? count + 1 : count;
-    } while (acl != NULL);
+        ace = GetACLResourceData(&subject, &savePtr);
+        count = (NULL != ace) ? count + 1 : count;
+    } while (ace != NULL);
 
     EXPECT_EQ(count, NUM_ACE_FOR_WILDCARD_IN_ACL1_DAT);
 
@@ -308,32 +378,40 @@ TEST(ACLResourceTest, GetACLResourceTests)
 
 static OCStackResult  populateAcl(OicSecAcl_t *acl,  int numRsrc)
 {
-     OCStackResult ret = OC_STACK_ERROR;
-    memcpy(acl->subject.id, "2222222222222222", sizeof(acl->subject.id));
-    acl->resourcesLen = (size_t)numRsrc;
-    acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
-    VERIFY_NON_NULL(TAG, acl->resources, ERROR);
-    acl->resources[0] = (char*)OICMalloc(strlen("/a/led")+1);
-    VERIFY_NON_NULL(TAG, acl->resources[0], ERROR);
-    OICStrcpy(acl->resources[0], strlen("/a/led")+1, "/a/led");
-    if(numRsrc == 2)
+    OCStackResult ret = OC_STACK_ERROR;
+    OicSecAce_t* ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+    VERIFY_NON_NULL(TAG, ace, ERROR);
+
+    memcpy(ace->subjectuuid.id, "2222222222222222", sizeof(ace->subjectuuid.id));
+    EXPECT_EQ(true, AddResourceToACE(ace, "/a/led", "oic.core", "oic.if.r"));
+    if(2 == numRsrc)
     {
-        acl->resources[1] = (char*)OICMalloc(strlen("/a/fan")+1);
-        VERIFY_NON_NULL(TAG, acl->resources[1], ERROR);
-        OICStrcpy(acl->resources[1], strlen("/a/fan")+1, "/a/fan");
+        EXPECT_EQ(true, AddResourceToACE(ace, "/a/fan", "oic.core", "oic.if.r"));
     }
-    acl->permission = 6;
+    ace->permission = 6;
+    LL_APPEND(acl->aces, ace);
+
     memcpy(acl->rownerID.id, "1111111111111111", sizeof(acl->rownerID.id));
 
     ret = OC_STACK_OK;
+
+    return ret;
 exit:
+    DeleteACLList(acl);
     return ret;
-
 }
 
 //'DELETE' ACL test
 TEST(ACLResourceTest, ACLDeleteWithSingleResourceTest)
 {
+    static OCPersistentStorage ps = OCPersistentStorage();
+    SetPersistentHandler(&ps, true);
+
+    OicSecAcl_t *defaultAcl = NULL;
+    EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&defaultAcl));
+    ASSERT_TRUE(defaultAcl != NULL);
+    EXPECT_EQ(OC_STACK_OK, SetDefaultACL(defaultAcl));
+
     //Populate ACL
     OicSecAcl_t acl = OicSecAcl_t();
     EXPECT_EQ(OC_STACK_OK, populateAcl(&acl, 1));
@@ -348,9 +426,6 @@ TEST(ACLResourceTest, ACLDeleteWithSingleResourceTest)
     OCSecurityPayload *securityPayload = OCSecurityPayloadCreate(payload, size);
     ASSERT_TRUE(NULL != securityPayload);
 
-    static OCPersistentStorage ps = OCPersistentStorage();
-    SetPersistentHandler(&ps, true);
-
     // Create Entity Handler POST request payload
     OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
     ehReq.payload = (OCPayload *) securityPayload;
@@ -358,13 +433,13 @@ TEST(ACLResourceTest, ACLDeleteWithSingleResourceTest)
     ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
 
     // Verify if SRM contains ACE for the subject
-    OicSecAcl_t* savePtr = NULL;
-    const OicSecAcl_t* subjectAcl1 = GetACLResourceData(&acl.subject, &savePtr);
-    ASSERT_TRUE(NULL != subjectAcl1);
+    OicSecAce_t* savePtr = NULL;
+    const OicSecAce_t* subjectAce1 = GetACLResourceData(&acl.aces->subjectuuid, &savePtr);
+    ASSERT_TRUE(NULL != subjectAce1);
 
     // Create Entity Handler DELETE request
     ehReq.method = OC_REST_DELETE;
-    char query[] = "subjectuuid=2222222222222222;resources=/a/led";
+    char query[] = "subjectuuid=32323232-3232-3232-3232-323232323232;resources=/a/led";
     ehReq.query = (char *)OICMalloc(strlen(query)+1);
     ASSERT_TRUE(NULL !=  ehReq.query);
     OICStrcpy(ehReq.query, strlen(query)+1, query);
@@ -372,8 +447,8 @@ TEST(ACLResourceTest, ACLDeleteWithSingleResourceTest)
 
     // Verify if SRM has deleted ACE for the subject
     savePtr = NULL;
-    const OicSecAcl_t* subjectAcl2 = GetACLResourceData(&acl.subject, &savePtr);
-    ASSERT_TRUE(NULL == subjectAcl2);
+    const OicSecAce_t* subjectAce2 = GetACLResourceData(&acl.aces->subjectuuid, &savePtr);
+    ASSERT_TRUE(NULL == subjectAce2);
 
     // Perform cleanup
     DeInitACLResource();
@@ -384,6 +459,14 @@ TEST(ACLResourceTest, ACLDeleteWithSingleResourceTest)
 
 TEST(ACLResourceTest, ACLDeleteWithMultiResourceTest)
 {
+    static OCPersistentStorage ps = OCPersistentStorage();
+    SetPersistentHandler(&ps, true);
+
+    OicSecAcl_t *defaultAcl = NULL;
+    EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&defaultAcl));
+    ASSERT_TRUE(defaultAcl != NULL);
+    EXPECT_EQ(OC_STACK_OK, SetDefaultACL(defaultAcl));
+
     //Populate ACL
     OicSecAcl_t acl = OicSecAcl_t();
     EXPECT_EQ(OC_STACK_OK, populateAcl(&acl, 2));
@@ -398,9 +481,6 @@ TEST(ACLResourceTest, ACLDeleteWithMultiResourceTest)
     OCSecurityPayload *securityPayload = OCSecurityPayloadCreate(payload, size);
     ASSERT_TRUE(NULL!= securityPayload);
 
-    static OCPersistentStorage ps = OCPersistentStorage();
-    SetPersistentHandler(&ps, true);
-
     // Create Entity Handler POST request payload
     OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
     ehReq.method = OC_REST_POST;
@@ -408,14 +488,22 @@ TEST(ACLResourceTest, ACLDeleteWithMultiResourceTest)
     ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
 
     // Verify if SRM contains ACE for the subject with two resources
-    OicSecAcl_t* savePtr = NULL;
-    const OicSecAcl_t* subjectAcl1 = GetACLResourceData(&acl.subject, &savePtr);
-    ASSERT_TRUE(NULL != subjectAcl1);
-    EXPECT_EQ(2, subjectAcl1->resourcesLen);
+    OicSecAce_t* savePtr = NULL;
+    const OicSecAce_t* subjectAce1 = GetACLResourceData(&acl.aces->subjectuuid, &savePtr);
+    ASSERT_TRUE(NULL != subjectAce1);
+    EXPECT_EQ(2, GetNumberOfResource(subjectAce1));
+
+    printf("\n\n");
+    OicSecRsrc_t* rsrc = NULL;
+    LL_FOREACH(subjectAce1->resources, rsrc)
+    {
+        printf("%s\n", rsrc->href);
+    }
+    printf("\n\n");
 
     // Create Entity Handler DELETE request
     ehReq.method = OC_REST_DELETE;
-    char query[] = "subjectuuid=2222222222222222;resources=/a/led";
+    char query[] = "subjectuuid=32323232-3232-3232-3232-323232323232;resources=/a/led";
     ehReq.query = (char *)OICMalloc(strlen(query)+1);
     ASSERT_TRUE(NULL != ehReq.query);
     OICStrcpy(ehReq.query, strlen(query)+1, query);
@@ -424,9 +512,9 @@ TEST(ACLResourceTest, ACLDeleteWithMultiResourceTest)
 
     // Verify if SRM contains ACL for the subject but only with one resource
     savePtr = NULL;
-    const OicSecAcl_t* subjectAcl2 = GetACLResourceData(&acl.subject, &savePtr);
-    ASSERT_TRUE(NULL != subjectAcl2);
-    EXPECT_EQ(1, subjectAcl2->resourcesLen);
+    const OicSecAce_t* subjectAce2 = GetACLResourceData(&acl.aces->subjectuuid, &savePtr);
+    ASSERT_TRUE(NULL != subjectAce2);
+    EXPECT_EQ(1, GetNumberOfResource(subjectAce2));
 
     // Perform cleanup
     OCPayloadDestroy((OCPayload *)securityPayload);
@@ -438,6 +526,14 @@ TEST(ACLResourceTest, ACLDeleteWithMultiResourceTest)
 //'GET' with query ACL test
 TEST(ACLResourceTest, ACLGetWithQueryTest)
 {
+    static OCPersistentStorage ps = OCPersistentStorage();
+    SetPersistentHandler(&ps, true);
+
+    OicSecAcl_t *defaultAcl = NULL;
+    EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&defaultAcl));
+    ASSERT_TRUE(defaultAcl != NULL);
+    EXPECT_EQ(OC_STACK_OK, SetDefaultACL(defaultAcl));
+
     //Populate ACL
     OicSecAcl_t acl = OicSecAcl_t();
     EXPECT_EQ(OC_STACK_OK, populateAcl(&acl, 1));
@@ -452,9 +548,6 @@ TEST(ACLResourceTest, ACLGetWithQueryTest)
     OCSecurityPayload *securityPayload = OCSecurityPayloadCreate(payload, size);
     ASSERT_TRUE(NULL != securityPayload);
 
-    static OCPersistentStorage ps = OCPersistentStorage();
-    SetPersistentHandler(&ps, true);
-
     //Create Entity Handler POST request payload
     OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
     ehReq.method = OC_REST_POST;
@@ -463,7 +556,7 @@ TEST(ACLResourceTest, ACLGetWithQueryTest)
 
     //Create Entity Handler GET request wit query
     ehReq.method = OC_REST_GET;
-    char query[] = "subjectuuid=2222222222222222;resources=/a/led";
+    char query[] = "subjectuuid=32323232-3232-3232-3232-323232323232;resources=/a/led";
     ehReq.query = (char*)OICMalloc(strlen(query)+1);
     ASSERT_TRUE(NULL != ehReq.query);
     OICStrcpy(ehReq.query, strlen(query)+1, query);
index fd63aa1..13fce86 100644 (file)
@@ -52,6 +52,7 @@ OicSecCred_t * getCredList()
 #endif
 
     cred->credType = SYMMETRIC_PAIR_WISE_KEY;
+    cred->privateData.encoding = OIC_ENCODING_RAW;
     cred->privateData.data = (uint8_t *)OICCalloc(1, strlen("My private Key11") + 1);
     VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
     OICStrcpy((char *)cred->privateData.data, strlen("My private Key11")+1,"My private Key11");
@@ -66,6 +67,7 @@ OicSecCred_t * getCredList()
     cred->next->roleIdsLen = 0;
 #endif
     cred->next->credType = SYMMETRIC_PAIR_WISE_KEY;
+    cred->next->privateData.encoding = OIC_ENCODING_RAW;
     sz = strlen("My private Key21") + 1;
     cred->next->privateData.data = (uint8_t *)OICCalloc(1, sz);
     VERIFY_NON_NULL(TAG, cred->next->privateData.data, ERROR);
@@ -110,7 +112,7 @@ static void printCred(const OicSecCred_t * cred)
            OIC_LOG_V(INFO, TAG, "cred->publicData.data = %s", credTmp1->publicData.data);
         }
 #endif /* __WITH_X509__ */
-       OIC_LOG_V(INFO, TAG, "cred->rownerID = %s", credTmp1->rownerID.id);
+    OIC_LOG_V(INFO, TAG, "cred->rownerID = %s", credTmp1->rownerID.id);
     }
 }
 
@@ -169,7 +171,8 @@ TEST(CredResourceTest, CredEntityHandlerDeleteTest)
     ASSERT_TRUE(NULL != cred);
     uint8_t *payload = NULL;
     size_t size = 0;
-    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred, &payload, &size));
+    int secureFlag = 0;
+    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred, &payload, &size, secureFlag));
     if (!payload)
     {
         DeleteCredList(cred);
@@ -219,8 +222,9 @@ TEST(CredResourceTest, CredEntityHandlerDeleteTest)
 
 TEST(CredResourceTest, CredToCBORPayloadNULL)
 {
+    int secureFlag = 0;
     OicSecCred_t *cred = getCredList();
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(NULL, NULL, 0));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(NULL, NULL, 0, secureFlag));
     size_t size = 0;
     uint8_t *cborPayload = (uint8_t *) OICCalloc(1, 10);
     if (!cborPayload)
@@ -228,12 +232,12 @@ TEST(CredResourceTest, CredToCBORPayloadNULL)
         DeleteCredList(cred);
     }
     ASSERT_TRUE(NULL != cborPayload);
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, &cborPayload, &size));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, &cborPayload, &size, secureFlag));
     OICFree(cborPayload);
     cborPayload = NULL;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(NULL, &cborPayload, &size));
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, &cborPayload, 0));
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, NULL, &size));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(NULL, &cborPayload, &size,secureFlag));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, &cborPayload, 0, secureFlag));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, NULL, &size, secureFlag));
     DeleteCredList(cred);
 }
 
@@ -241,9 +245,10 @@ TEST(CredResourceTest, CredToCBORPayloadVALID)
 {
     uint8_t* payload = NULL;
     size_t size = 0;
+    int secureFlag = 0;
     OicSecCred_t *cred = getCredList();
 
-    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred, &payload, &size));
+    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred, &payload, &size, secureFlag));
     if (!payload)
     {
         DeleteCredList(cred);
@@ -260,7 +265,8 @@ TEST(CredResourceTest, CBORPayloadToCredVALID)
 
     uint8_t *payload = NULL;
     size_t size = 0;
-    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred1, &payload, &size));
+    int secureFlag = 0;
+    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred1, &payload, &size, secureFlag));
     DeleteCredList(cred1);
     ASSERT_TRUE(NULL != payload);
 
@@ -271,6 +277,33 @@ TEST(CredResourceTest, CBORPayloadToCredVALID)
     DeleteCredList(cred2);
 }
 
+TEST(CredResourceTest, CBORPayloadToCredSecureVALID)
+{
+    OicSecCred_t *cred1 = getCredList();
+    ASSERT_TRUE(NULL != cred1);
+    cred1->privateData.data = (uint8_t *)OICCalloc(1, OWNER_PSK_LENGTH_128);
+    ASSERT_TRUE(NULL != cred1->privateData.data);
+    cred1->privateData.len = OWNER_PSK_LENGTH_128;
+
+    uint8_t *payload = NULL;
+    size_t size = 0;
+    int secureFlag = 1;
+    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred1, &payload, &size, secureFlag));
+
+    ASSERT_TRUE(NULL != payload);
+
+    OicSecCred_t *cred2 = NULL;
+    EXPECT_EQ(OC_STACK_OK, CBORPayloadToCred(payload, size, &cred2));
+    ASSERT_TRUE(cred2 != NULL);
+    ASSERT_TRUE(NULL == cred2->privateData.data);
+    ASSERT_TRUE(0 == cred2->privateData.len);
+
+    OICFree(payload);
+
+    DeleteCredList(cred1);
+    DeleteCredList(cred2);
+}
+
 TEST(CredResourceTest, CBORPayloadToCredNULL)
 {
     OicSecCred_t *cred = NULL;
@@ -357,3 +390,61 @@ TEST(CredGetResourceDataTest, GetCredResourceDataValidSubject)
     EXPECT_TRUE(NULL != GetCredResourceData(cred->subject));
 }
 #endif
+
+#ifdef __WITH_X509__
+#include <stdlib.h>
+
+static char PROV_TOOL_DB_FILE[] = "/oic_svr_db_prov.dat";
+
+#define STRINGIZE2(x) #x
+#define STRINGIZE(x) STRINGIZE2(x)
+
+static FILE *client_fopen(const char* UNUSED_PARAM , const char *mode)
+{
+    (void)UNUSED_PARAM;
+
+    int len = strlen(STRINGIZE(SECURITY_BUILD_UNITTEST_DIR)) + strlen(PROV_TOOL_DB_FILE) + 1;
+    char *filepath = (char *)OICCalloc(1, len);
+
+    if (!filepath)
+    {
+        printf("filepath memory allocation failed. \n");
+        return NULL;
+    }
+
+    snprintf(filepath, len, "%s%s", STRINGIZE(SECURITY_BUILD_UNITTEST_DIR), PROV_TOOL_DB_FILE);
+
+    FILE* file =  fopen(filepath, mode);
+    OICFree(filepath);
+    return file;
+}
+
+static OCPersistentStorage ps = { client_fopen, fread, fwrite, fclose, unlink };
+
+//GetDtlsX509Credentials Test
+TEST(CredResourceTest, GetDtlsX509Credentials)
+{
+    ASSERT_EQ(OC_STACK_OK, OCInit(NULL, 0, OC_CLIENT_SERVER));
+    OCRegisterPersistentStorageHandler(&ps);
+    InitCredResource();
+    CADtlsX509Creds_t g_X509Cred = {{0}, 0, 0, {0}, {0}, {0}};
+    EXPECT_EQ(0, GetDtlsX509Credentials(&g_X509Cred));
+}
+
+#endif
+#if defined(__WITH_DTLS__)
+TEST(CredGetDtlsPskCredentialsTest, NullResult)
+{
+    EXPECT_EQ(-1, GetDtlsPskCredentials(CA_DTLS_PSK_KEY, NULL, 0, NULL, 0));
+}
+
+TEST(CredAddTmpPskWithPINTest, NullSubject)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, AddTmpPskWithPIN(NULL, SYMMETRIC_PAIR_WISE_KEY,
+              NULL, 0, NULL, NULL));
+}
+#endif
+TEST(CredCBORPayloadToCredTest, NullPayload)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(NULL, 0, NULL));
+}
diff --git a/resource/csdk/security/unittest/crlresourcetest.cpp b/resource/csdk/security/unittest/crlresourcetest.cpp
new file mode 100644 (file)
index 0000000..d7c17ef
--- /dev/null
@@ -0,0 +1,113 @@
+/******************************************************************
+*
+* 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.
+*
+******************************************************************/
+#ifdef __WITH_X509__
+
+#include "gtest/gtest.h"
+#include "logger.h"
+#include "ocpayload.h"
+#include "ocstack.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "resourcemanager.h"
+#include "crlresource.h"
+#include "securevirtualresourcetypes.h"
+#include "srmtestcommon.h"
+#include "srmutility.h"
+#include "psinterface.h"
+#include "security_internals.h"
+#include "crl.h"
+
+#define TAG  "SRM-CRL-UT"
+
+void DeleteCrl(OicSecCrl_t *crl)
+{
+    if (crl)
+    {
+        //Clean ThisUpdate
+        OICFree(crl->ThisUpdate.data);
+        crl->ThisUpdate.data = NULL;
+        //clean CrlData
+        OICFree(crl->CrlData.data);
+        crl->CrlData.data = NULL;
+        //Clean crl itself
+        OICFree(crl);
+        crl = NULL;
+    }
+}
+
+ //InitCRLResource Tests
+TEST(CRLResourceTest, InitCRLResource)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, InitCRLResource());
+}
+
+//DeInitCredResource Tests
+TEST(CRLResourceTest, DeInitCRLResource)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitCRLResource());
+}
+
+//GetCRLResource Tests
+TEST(CRLResourceTest, GetCRLResource)
+{
+    OicSecCrl_t *nullCrl = GetCRLResource();
+    EXPECT_NE((OicSecCrl_t*)NULL, nullCrl);
+    DeleteCrl(nullCrl);
+}
+
+//CrlToCBORPayload Tests
+TEST(CRLResourceTest, CrlToCBORPayload)
+{
+    uint8_t *payload = NULL;
+    size_t size;
+    OicSecCrl_t *crl = GetCRLResource();
+    ASSERT_TRUE(NULL != crl);
+    size = crl->CrlData.len;
+    EXPECT_EQ(OC_STACK_OK, CrlToCBORPayload(crl, &payload, &size));
+    DeleteCrl(crl);
+    OICFree(payload);
+}
+
+//CBORPaylodToCrl Tests
+TEST(CRLResourceTest, CBORPayloadToCrl)
+{
+    uint8_t *payload = NULL;
+    size_t size;
+    OicSecCrl_t *crl = GetCRLResource();
+    ASSERT_TRUE(NULL != crl);
+    size = crl->CrlData.len;
+    EXPECT_EQ(OC_STACK_OK, CrlToCBORPayload(crl, &payload, &size));
+    DeleteCrl(crl);
+    crl = NULL;
+    EXPECT_EQ(OC_STACK_OK, CBORPayloadToCrl(payload, size, &crl));
+    DeleteCrl(crl);
+    OICFree(payload);
+}
+
+//GetDerCrl Tests
+TEST(CRLResourceTest, GetDerCrl)
+{
+    uint8_t crlData[CRL_MAX_LEN] = {0};
+    ByteArray crlArray = {crlData, CRL_MAX_LEN};
+    GetDerCrl(&crlArray);
+    EXPECT_NE(0, crlArray.len);
+}
+
+#endif
index 5c49a21..4904b35 100644 (file)
@@ -29,20 +29,21 @@ static OCDirectPairingDev_t peer;
 static OicSecPrm_t pmSel;
 static char pinNumber;
 
-static void ResultCB(OCDirectPairingDev_t *UNUSED1, OCStackResult UNUSED2)
+static void ResultCB(void *UNUSED1, OCDirectPairingDev_t *UNUSED2, OCStackResult UNUSED3)
 {
     //dummy callback
     (void) UNUSED1;
     (void) UNUSED2;
+    (void) UNUSED3;
 }
 
 TEST(DPDirectPairingTest, NullPeer)
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, DPDirectPairing(NULL, pmSel, &pinNumber, &ResultCB));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DPDirectPairing(NULL, NULL, pmSel, &pinNumber, &ResultCB));
 }
 
 TEST(DPDirectPairingTest, NullPinNumber)
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, DPDirectPairing(&peer, pmSel, NULL, &ResultCB));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DPDirectPairing(NULL, &peer, pmSel, NULL, &ResultCB));
 }
 
index 6c1c20d..80eb186 100644 (file)
@@ -85,6 +85,31 @@ static void printRecur(IotvtICalRecur_t *recur)
     }
 }
 
+#ifndef HAVE_LOCALTIME_R
+
+#define localtime_r localtime_r_compat
+
+/**
+ * @description An implementation of `localtime_r` for systems which only
+ * have a `localtime` implementation.
+ */
+static tm* localtime_r_compat(const time_t* timer, tm* result)
+{
+    if (NULL == result)
+    {
+        OIC_LOG(ERROR, TAG, "localtime_r received null results parameter");
+    }
+
+    if (NULL == timer)
+    {
+        OIC_LOG(WARNING, TAG, "localtime_r received null timer parameter");
+    }
+
+    tm* tempPtr = localtime(timer);
+    memcpy(result, tempPtr, sizeof(tm));
+    return result;
+}
+#endif
 
 static void checkValidityOfRequest(char *recurStr, char *periodStr,int startTime, int endTime,
                                     int byDay)
index c048b16..66afe9c 100644 (file)
Binary files a/resource/csdk/security/unittest/oic_svr_db.dat and b/resource/csdk/security/unittest/oic_svr_db.dat differ
index 7c86ab3..59fa154 100644 (file)
@@ -8,32 +8,20 @@
                         {
                             "href": "/oic/res",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.wk.res"],
+                            "if": ["oic.if.ll"]
                         },
                         {
                             "href": "/oic/d",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.wk.d"],
+                            "if": ["oic.if.baseline", "oic.if.r"]
                         },
                         {
                             "href": "/oic/p",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
-                        },
-                        {
-                            "href": "/oic/res/types/d",
-                            "rel": "",
-                            "rt": "",
-                            "if": ""
-                        },
-                        {
-                            "href": "/oic/ad",
-                            "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.wk.p"],
+                            "if": ["oic.if.baseline", "oic.if.r"]
                         }
                     ],
                     "permission": 2
                         {
                             "href": "/oic/sec/doxm",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.doxm"],
+                            "if": ["oic.if.baseline"]
                         },
                         {
                             "href": "/oic/sec/pstat",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.pstat"],
+                            "if": ["oic.if.baseline"]
                         },
                         {
                             "href": "/oic/sec/acl",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.acl"],
+                            "if": ["oic.if.baseline"]
                         }
                     ],
                     "permission": 6
                         {
                             "href": "/oic/sec/pconf",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.pconf"],
+                            "if": ["oic.if.baseline"]
                         },
                         {
                             "href": "/oic/sec/dpairing",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.dpairing"],
+                            "if": ["oic.if.baseline"]
                         }
                     ],
                     "permission": 6
         "deviceuuid": "756E6B6E-6F77-6564-4465-766963654964",
         "devowneruuid": "",
         "rowneruuid": "756E6B6E-6F77-6564-4465-766963654964",
-        "dpc": true
+        "x.com.samsung.dpc": true
     }
 }
\ No newline at end of file
diff --git a/resource/csdk/security/unittest/oic_svr_db_prov.dat b/resource/csdk/security/unittest/oic_svr_db_prov.dat
new file mode 100644 (file)
index 0000000..2f8f4df
Binary files /dev/null and b/resource/csdk/security/unittest/oic_svr_db_prov.dat differ
index e022892..4befed0 100644 (file)
Binary files a/resource/csdk/security/unittest/oic_unittest.dat and b/resource/csdk/security/unittest/oic_unittest.dat differ
index 922be86..c435721 100644 (file)
@@ -8,17 +8,17 @@
                         {
                             "href": "/oic/light",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.core"],
+                            "if": ["oic.if.baseline"]
                         },
                         {
                             "href": "/oic/fan",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.core"],
+                            "if": ["oic.if.baseline"]
                         }
                     ],
-                    "permission": 31        
+                    "permission": 31
                 },
                 {
                     "subjectuuid": "33333333-3333-3333-3333-333333333333",
                         {
                             "href": "/oic/light",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.core"],
+                            "if": ["oic.if.baseline"]
                         },
                         {
                             "href": "/oic/garage",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.core"],
+                            "if": ["oic.if.baseline"]
                         }
                     ],
-                    "permission": 31        
+                    "permission": 31
                 }
             ]
         },
index 93c8370..9b91532 100644 (file)
@@ -1 +1 @@
-¿caclY\ 2\8b¢faclist¡daces\84£ksubjectuuida*iresources\86¤dhrefh/oic/rescrel`brt`bif`¤dhreff/oic/dcrel`brt`bif`¤dhreff/oic/pcrel`brt`bif`¤dhrefp/oic/res/types/dcrel`brt`bif`¤dhrefg/oic/adcrel`brt`bif`¤dhrefl/oic/sec/aclcrel`brt`bif`jpermission\ 2£ksubjectuuida*iresources\82¤dhrefm/oic/sec/doxmcrel`brt`bif`¤dhrefn/oic/sec/pstatcrel`brt`bif`jpermission\ 6£ksubjectuuidx$31313131-3131-3131-3131-313131313131iresources\82¤dhrefj/oic/lightcrel`brt`bif`¤dhrefh/oic/fancrel`brt`bif`jpermission\18\1f£ksubjectuuidx$33333333-3333-3333-3333-333333333333iresources\82¤dhrefj/oic/lightcrel`brt`bif`¤dhrefk/oic/garagecrel`brt`bif`jpermission\18\1fjrowneruuidx$32323232-3232-3232-3232-323232323232ÿ
\ No newline at end of file
+¿caclY\ 3 Â¢faclist¡daces\84£ksubjectuuida*iresources\83¤dhrefh/oic/resbrt\81joic.wk.resbif\81ioic.if.llcrel`¤dhreff/oic/dbrt\81hoic.wk.dbif\82ooic.if.baselinehoic.if.rcrel`¤dhreff/oic/pbrt\81hoic.wk.pbif\82ooic.if.baselinehoic.if.rcrel`jpermission\ 2£ksubjectuuida*iresources\82¤dhrefm/oic/sec/doxmbrt\81joic.r.doxmbif\81ooic.if.baselinecrel`¤dhrefn/oic/sec/pstatbrt\81koic.r.pstatbif\81ooic.if.baselinecrel`jpermission\ 6£ksubjectuuidx$31313131-3131-3131-3131-313131313131iresources\82¤dhrefj/oic/lightbrt\81hoic.corebif\81ooic.if.baselinecrel`¤dhrefh/oic/fanbrt\81hoic.corebif\81ooic.if.baselinecrel`jpermission\18\1f£ksubjectuuidx$33333333-3333-3333-3333-333333333333iresources\82¤dhrefj/oic/lightbrt\81hoic.corebif\81ooic.if.baselinecrel`¤dhrefk/oic/garagebrt\81hoic.corebif\81ooic.if.baselinecrel`jpermission\18\1fjrowneruuidx$32323232-3232-3232-3232-323232323232ÿ
\ No newline at end of file
index 7dd810f..7dbb78b 100644 (file)
@@ -8,38 +8,20 @@
                         {
                             "href": "/oic/res",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.wk.res"],
+                            "if": ["oic.if.ll"]
                         },
                         {
                             "href": "/oic/d",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.wk.d"],
+                            "if": ["oic.if.baseline", "oic.if.r"]
                         },
                         {
                             "href": "/oic/p",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
-                        },
-                        {
-                            "href": "/oic/res/types/d",
-                            "rel": "",
-                            "rt": "",
-                            "if": ""
-                        },
-                        {
-                            "href": "/oic/ad",
-                            "rel": "",
-                            "rt": "",
-                            "if": ""
-                        },
-                        {
-                            "href": "/oic/sec/acl",
-                            "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.wk.p"],
+                            "if": ["oic.if.baseline", "oic.if.r"]
                         }
                     ],
                     "permission": 2
                         {
                             "href": "/oic/sec/doxm",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.doxm"],
+                            "if": ["oic.if.baseline"]
                         },
                         {
                             "href": "/oic/sec/pstat",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.pstat"],
+                            "if": ["oic.if.baseline"]
                         }
                     ],
                     "permission": 6
                         {
                             "href": "/oic/light",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.core"],
+                            "if": ["oic.if.baseline"]
                         },
                         {
                             "href": "/oic/fan",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.core"],
+                            "if": ["oic.if.baseline"]
                         }
                     ],
-                    "permission": 31        
+                    "permission": 31
                 },
                 {
                     "subjectuuid": "33333333-3333-3333-3333-333333333333",
                         {
                             "href": "/oic/light",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.core"],
+                            "if": ["oic.if.baseline"]
                         },
                         {
                             "href": "/oic/garage",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.core"],
+                            "if": ["oic.if.baseline"]
                         }
                     ],
-                    "permission": 31        
+                    "permission": 31
                 }
             ]
         },
index e9efbb5..064d997 100644 (file)
@@ -1 +1 @@
-¿caclY\ 1X¢faclist¡daces\81£ksubjectuuida*iresources\88¤dhrefh/oic/rescrel`brt`bif`¤dhreff/oic/dcrel`brt`bif`¤dhreff/oic/pcrel`brt`bif`¤dhrefp/oic/res/types/dcrel`brt`bif`¤dhrefg/oic/adcrel`brt`bif`¤dhrefl/oic/sec/aclcrel`brt`bif`¤dhrefm/oic/sec/doxmcrel`brt`bif`¤dhrefn/oic/sec/pstatcrel`brt`bif`jpermission\ 2jrowneruuidx$32323232-3232-3232-3232-323232323232ÿ
\ No newline at end of file
+¿caclY\ 1âfaclist¡daces\81£ksubjectuuida*iresources\86¤dhrefh/oic/resbrt\81joic.wk.resbif\81ioic.if.llcrel`¤dhreff/oic/dbrt\81hoic.wk.dbif\82ooic.if.baselinehoic.if.rcrel`¤dhreff/oic/pbrt\81hoic.wk.pbif\82ooic.if.baselinehoic.if.rcrel`¤dhrefm/oic/sec/doxmbrt\81joic.r.doxmbif\81ooic.if.baselinecrel`¤dhrefn/oic/sec/pstatbrt\81koic.r.pstatbif\81ooic.if.baselinecrel`¤dhrefl/oic/sec/aclbrt\81ioic.r.aclbif\81ooic.if.baselinecrel`jpermission\ 2jrowneruuidx$32323232-3232-3232-3232-323232323232ÿ
\ No newline at end of file
index d624da5..df8739a 100644 (file)
@@ -8,50 +8,38 @@
                         {
                             "href": "/oic/res",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.wk.res"],
+                            "if": ["oic.if.ll"]
                         },
                         {
                             "href": "/oic/d",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.wk.d"],
+                            "if": ["oic.if.baseline", "oic.if.r"]
                         },
                         {
                             "href": "/oic/p",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.wk.p"],
+                            "if": ["oic.if.baseline", "oic.if.r"]
                         },
                         {
-                            "href": "/oic/res/types/d",
+                            "href": "/oic/sec/doxm",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.doxm"],
+                            "if": ["oic.if.baseline"]
                         },
                         {
-                            "href": "/oic/ad",
+                            "href": "/oic/sec/pstat",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.pstat"],
+                            "if": ["oic.if.baseline"]
                         },
                         {
                             "href": "/oic/sec/acl",
                             "rel": "",
-                            "rt": "",
-                            "if": ""
-                        },
-                        {
-                            "href": "/oic/sec/doxm",
-                            "rel": "",
-                            "rt": "",
-                            "if": ""
-                        },
-                        {
-                            "href": "/oic/sec/pstat",
-                            "rel": "",
-                            "rt": "",
-                            "if": ""
+                            "rt": ["oic.r.acl"],
+                            "if": ["oic.if.baseline"]
                         }
                     ],
                     "permission": 2
index 4806a96..b73881d 100644 (file)
@@ -19,9 +19,6 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
-#include <pwd.h>
-#include <grp.h>
-#include <linux/limits.h>
 #include "ocstack.h"
 #include "cainterface.h"
 #include "srmresourcestrings.h"
index d1c9396..b9e5ceb 100644 (file)
@@ -18,7 +18,9 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 #include "gtest/gtest.h"
 
 #include "ocpayload.h"
index 95cf63c..2917709 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
+#ifdef HAVE_PWD_H
 #include <pwd.h>
+#endif
+#ifdef HAVE_GRP_H
 #include <grp.h>
+#endif
+#ifdef HAVE_LINUX_LIMITS_H
 #include <linux/limits.h>
+#endif
 #include "ocstack.h"
 #include "cainterface.h"
 #include "secureresourcemanager.h"
@@ -119,6 +125,12 @@ TEST(PersistentStorageHandlerTest, RegisterValidHandler)
     EXPECT_TRUE(&gpsi == ps);
 }
 
+#if !(defined(HAVE_LINUX_LIMITS_H) && defined(HAVE_PWD_H))
+TEST(PersistentStorageHandlerTest, DISABLED_PersistentStorageValidHandlers)
+{
+    /** @todo: Implement test on non-Linux platform */
+}
+#else
 TEST(PersistentStorageHandlerTest, PersistentStorageValidHandlers)
 {
     OCPersistentStorage *psi = SRMGetPersistentStorageHandler();
@@ -157,3 +169,5 @@ TEST(PersistentStorageHandlerTest, PersistentStorageValidHandlers)
     }
     psi->unlink(outFilePath);
 }
+#endif
+
index 1435ad5..5bfe64e 100644 (file)
@@ -28,7 +28,7 @@
 #define STRINGIZE(x) STRINGIZE2(x)
 
 // TODO: Remove this, once all cbor related are completed.
-char* ReadFile(const char* filename)
+char* ReadFileToBuffer(const char* filename)
 {
 
     FILE *fp = NULL;
index ff5c453..8b81e91 100644 (file)
@@ -21,7 +21,7 @@
 #ifndef IOTVT_SRM_TEST_COMMON_H
 #define IOTVT_SRM_TEST_COMMON_H
 
-char* ReadFile(const char* filename);
+char* ReadFileToBuffer(const char* filename);
 bool ReadCBORFile(const char* filename, const char* rsrcName, uint8_t **payload, size_t *size);
 void SetPersistentHandler(OCPersistentStorage *ps, bool set);
 
index 052afad..8444694 100644 (file)
 extern "C"
 {
 #endif
-OCStackResult OCParsePayload(OCPayload** outPayload, OCPayloadType type,
+OC_EXPORT_TEST OCStackResult OCParsePayload(OCPayload** outPayload, OCPayloadType type,
         const uint8_t* payload, size_t payloadSize);
 
-OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t* size);
+OC_EXPORT_TEST OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t* size);
 
 #ifdef __cplusplus
 }
index ee48b7e..d7f7bae 100644 (file)
@@ -252,7 +252,8 @@ OCStackResult FormOCEntityHandlerRequest(
         uint8_t numVendorOptions,
         OCHeaderOption * vendorOptions,
         OCObserveAction observeAction,
-        OCObservationId observeID);
+        OCObservationId observeID,
+        uint16_t messageID);
 
 /**
  * Find a server request in the server request list and delete
index bef3e98..241f588 100644 (file)
@@ -66,8 +66,8 @@ extern void* defaultDeviceHandlerCallbackParameter;
 /** The coap scheme */
 #define OC_COAP_SCHEME "coap://"
 
-/** the first outgoing sequence number will be 5*/
-#define OC_OFFSET_SEQUENCE_NUMBER (4)
+/** the first outgoing sequence number will be 2*/
+#define OC_OFFSET_SEQUENCE_NUMBER (1)
 
 /**
  * This structure will be created in occoap and passed up the stack on the server side.
@@ -266,6 +266,14 @@ OCStackResult BindResourceTypeToResource(OCResource* resource,
 OCStackResult CAResultToOCResult(CAResult_t caResult);
 
 /**
+ * Converts a OCStackResult type to a bool type.
+ *
+ * @param ocResult OCStackResult value to convert.
+ * @return true on success, false upon failure.
+ */
+bool OCResultToSuccess(OCStackResult ocResult);
+
+/**
  * Map OCQualityOfService to CAMessageType.
  *
  * @param qos Input qos.
@@ -289,9 +297,9 @@ OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
         OCResourceProperty resourceProperties, uint8_t enable);
 #endif
 
-const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
+OC_EXPORT const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
 
-OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
+OC_EXPORT OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
 
 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out);
 
index 4b62813..d5c727e 100644 (file)
@@ -60,33 +60,34 @@ extern "C"
 
 typedef struct OCResource OCResource;
 
-void OCPayloadDestroy(OCPayload* payload);
+OC_EXPORT void OCPayloadDestroy(OCPayload* payload);
 
 // Representation Payload
-OCRepPayload* OCRepPayloadCreate();
+OC_EXPORT OCRepPayload* OCRepPayloadCreate();
 
-size_t calcDimTotal(const size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+OC_EXPORT size_t calcDimTotal(const size_t dimensions[MAX_REP_ARRAY_DEPTH]);
 
-OCRepPayload* OCRepPayloadClone(const OCRepPayload* payload);
+OC_EXPORT OCRepPayload* OCRepPayloadClone(const OCRepPayload* payload);
 
-void OCRepPayloadAppend(OCRepPayload* parent, OCRepPayload* child);
+OC_EXPORT void OCRepPayloadAppend(OCRepPayload* parent, OCRepPayload* child);
 
-bool OCRepPayloadSetUri(OCRepPayload* payload, const char* uri);
+OC_EXPORT bool OCRepPayloadSetUri(OCRepPayload* payload, const char* uri);
 
-bool OCRepPayloadAddResourceType(OCRepPayload* payload, const char* resourceType);
-bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* interface);
+OC_EXPORT bool OCRepPayloadAddResourceType(OCRepPayload* payload, const char* resourceType);
+OC_EXPORT bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* iface);
+OC_EXPORT bool OCRepPayloadAddModelVersion(OCRepPayload* payload, const char* dmv);
 
-bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceType);
-bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface);
+OC_EXPORT bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceType);
+OC_EXPORT bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* iface);
 
-bool OCRepPayloadIsNull(const OCRepPayload* payload, const char* name);
-bool OCRepPayloadSetNull(OCRepPayload* payload, const char* name);
+OC_EXPORT bool OCRepPayloadIsNull(const OCRepPayload* payload, const char* name);
+OC_EXPORT bool OCRepPayloadSetNull(OCRepPayload* payload, const char* name);
 
-bool OCRepPayloadSetPropInt(OCRepPayload* payload, const char* name, int64_t value);
-bool OCRepPayloadGetPropInt(const OCRepPayload* payload, const char* name, int64_t* value);
+OC_EXPORT bool OCRepPayloadSetPropInt(OCRepPayload* payload, const char* name, int64_t value);
+OC_EXPORT bool OCRepPayloadGetPropInt(const OCRepPayload* payload, const char* name, int64_t* value);
 
-bool OCRepPayloadSetPropDouble(OCRepPayload* payload, const char* name, double value);
-bool OCRepPayloadGetPropDouble(const OCRepPayload* payload, const char* name, double* value);
+OC_EXPORT bool OCRepPayloadSetPropDouble(OCRepPayload* payload, const char* name, double value);
+OC_EXPORT bool OCRepPayloadGetPropDouble(const OCRepPayload* payload, const char* name, double* value);
 
 /**
  * This function allocates memory for the byte string and sets it in the payload.
@@ -97,7 +98,7 @@ bool OCRepPayloadGetPropDouble(const OCRepPayload* payload, const char* name, do
  *
  * @return true on success, false upon failure.
  */
-bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCByteString value);
+OC_EXPORT bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCByteString value);
 
 /**
  * This function sets the byte string in the payload.
@@ -108,7 +109,7 @@ bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCBy
  *
  * @return true on success, false upon failure.
  */
-bool OCRepPayloadSetPropByteStringAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetPropByteStringAsOwner(OCRepPayload* payload, const char* name,
         OCByteString* value);
 
 /**
@@ -122,20 +123,19 @@ bool OCRepPayloadSetPropByteStringAsOwner(OCRepPayload* payload, const char* nam
  *
  * @return true on success, false upon failure.
  */
-bool OCRepPayloadGetPropByteString(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetPropByteString(const OCRepPayload* payload, const char* name,
         OCByteString* value);
 
-bool OCRepPayloadSetPropString(OCRepPayload* payload, const char* name, const char* value);
-bool OCRepPayloadSetPropStringAsOwner(OCRepPayload* payload, const char* name, char* value);
-bool OCRepPayloadGetPropString(const OCRepPayload* payload, const char* name, char** value);
+OC_EXPORT bool OCRepPayloadSetPropString(OCRepPayload* payload, const char* name, const char* value);
+OC_EXPORT bool OCRepPayloadSetPropStringAsOwner(OCRepPayload* payload, const char* name, char* value);
+OC_EXPORT bool OCRepPayloadGetPropString(const OCRepPayload* payload, const char* name, char** value);
 
-bool OCRepPayloadSetPropBool(OCRepPayload* payload, const char* name, bool value);
-bool OCRepPayloadGetPropBool(const OCRepPayload* payload, const char* name, bool* value);
+OC_EXPORT bool OCRepPayloadSetPropBool(OCRepPayload* payload, const char* name, bool value);
+OC_EXPORT bool OCRepPayloadGetPropBool(const OCRepPayload* payload, const char* name, bool* value);
 
-bool OCRepPayloadSetPropObject(OCRepPayload* payload, const char* name, const OCRepPayload* value);
-bool OCRepPayloadSetPropObjectAsOwner(OCRepPayload* payload, const char* name,
-        OCRepPayload* value);
-bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OCRepPayload** value);
+OC_EXPORT bool OCRepPayloadSetPropObject(OCRepPayload* payload, const char* name, const OCRepPayload* value);
+OC_EXPORT bool OCRepPayloadSetPropObjectAsOwner(OCRepPayload* payload, const char* name, OCRepPayload* value);
+OC_EXPORT bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OCRepPayload** value);
 
 /**
  * This function allocates memory for the byte string array and sets it in the payload.
@@ -147,7 +147,7 @@ bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OC
  *
  * @return true on success, false upon failure.
  */
-bool OCRepPayloadSetByteStringArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetByteStringArrayAsOwner(OCRepPayload* payload, const char* name,
         OCByteString* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
 
 /**
@@ -160,7 +160,7 @@ bool OCRepPayloadSetByteStringArrayAsOwner(OCRepPayload* payload, const char* na
  *
  * @return true on success, false upon failure.
  */
-bool OCRepPayloadSetByteStringArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetByteStringArray(OCRepPayload* payload, const char* name,
         const OCByteString* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
 
 /**
@@ -176,82 +176,103 @@ bool OCRepPayloadSetByteStringArray(OCRepPayload* payload, const char* name,
  *
  * @return true on success, false upon failure.
  */
-bool OCRepPayloadGetByteStringArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetByteStringArray(const OCRepPayload* payload, const char* name,
         OCByteString** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
 
-bool OCRepPayloadSetIntArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetIntArrayAsOwner(OCRepPayload* payload, const char* name,
         int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetIntArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetIntArray(OCRepPayload* payload, const char* name,
         const int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetIntArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetIntArray(const OCRepPayload* payload, const char* name,
         int64_t** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
 
-bool OCRepPayloadSetDoubleArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetDoubleArrayAsOwner(OCRepPayload* payload, const char* name,
         double* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetDoubleArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetDoubleArray(OCRepPayload* payload, const char* name,
         const double* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetDoubleArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetDoubleArray(const OCRepPayload* payload, const char* name,
         double** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
 
-bool OCRepPayloadSetStringArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetStringArrayAsOwner(OCRepPayload* payload, const char* name,
         char** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetStringArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetStringArray(OCRepPayload* payload, const char* name,
         const char** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetStringArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetStringArray(const OCRepPayload* payload, const char* name,
         char*** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
 
-bool OCRepPayloadSetBoolArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetBoolArrayAsOwner(OCRepPayload* payload, const char* name,
         bool* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetBoolArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetBoolArray(OCRepPayload* payload, const char* name,
         const bool* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetBoolArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetBoolArray(const OCRepPayload* payload, const char* name,
         bool** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
 
-bool OCRepPayloadSetPropObjectArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetPropObjectArrayAsOwner(OCRepPayload* payload, const char* name,
         OCRepPayload** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetPropObjectArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetPropObjectArray(OCRepPayload* payload, const char* name,
         const OCRepPayload** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetPropObjectArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetPropObjectArray(const OCRepPayload* payload, const char* name,
         OCRepPayload*** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
 
-void OCRepPayloadDestroy(OCRepPayload* payload);
+OC_EXPORT void OCRepPayloadDestroy(OCRepPayload* payload);
 
 // Discovery Payload
-OCDiscoveryPayload* OCDiscoveryPayloadCreate();
+OC_EXPORT OCDiscoveryPayload* OCDiscoveryPayloadCreate();
 
-OCSecurityPayload* OCSecurityPayloadCreate(const uint8_t* securityData, size_t size);
-void OCSecurityPayloadDestroy(OCSecurityPayload* payload);
+OC_EXPORT OCSecurityPayload* OCSecurityPayloadCreate(const uint8_t* securityData, size_t size);
+OC_EXPORT void OCSecurityPayloadDestroy(OCSecurityPayload* payload);
 
-void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
-                                   uint16_t securePort, uint16_t tcpPort);
-void OCDiscoveryPayloadAddNewResource(OCDiscoveryPayload* payload, OCResourcePayload* res);
-bool OCResourcePayloadAddStringLL(OCStringLL **payload, const char* type);
+#ifndef TCP_ADAPTER
+OC_EXPORT void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
+                                             uint16_t securePort);
+#else
+OC_EXPORT void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
+                                             uint16_t securePort, uint16_t tcpPort);
+#endif
+OC_EXPORT void OCDiscoveryPayloadAddNewResource(OCDiscoveryPayload* payload, OCResourcePayload* res);
+OC_EXPORT bool OCResourcePayloadAddStringLL(OCStringLL **payload, const char* type);
 
-size_t OCDiscoveryPayloadGetResourceCount(OCDiscoveryPayload* payload);
-OCResourcePayload* OCDiscoveryPayloadGetResource(OCDiscoveryPayload* payload, size_t index);
+OC_EXPORT size_t OCDiscoveryPayloadGetResourceCount(OCDiscoveryPayload* payload);
+OC_EXPORT OCResourcePayload* OCDiscoveryPayloadGetResource(OCDiscoveryPayload* payload, size_t index);
 
-void OCDiscoveryResourceDestroy(OCResourcePayload* payload);
-void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload);
+OC_EXPORT void OCDiscoveryResourceDestroy(OCResourcePayload* payload);
+OC_EXPORT void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload);
 
 // Device Payload
-OCDevicePayload* OCDevicePayloadCreate(const char* sid, const char* dname,
+OC_EXPORT OCDevicePayload* OCDevicePayloadCreate(const char* sid, const char* dname,
         const OCStringLL *types, const char* specVer, const char* dmVer);
-void OCDevicePayloadDestroy(OCDevicePayload* payload);
+OC_EXPORT void OCDevicePayloadDestroy(OCDevicePayload* payload);
 
 // Platform Payload
-OCPlatformPayload* OCPlatformPayloadCreate(const OCPlatformInfo* platformInfo);
-OCPlatformPayload* OCPlatformPayloadCreateAsOwner(OCPlatformInfo* platformInfo);
-void OCPlatformInfoDestroy(OCPlatformInfo *info);
-void OCPlatformPayloadDestroy(OCPlatformPayload* payload);
+OC_EXPORT OCPlatformPayload* OCPlatformPayloadCreate(const OCPlatformInfo* platformInfo);
+OC_EXPORT OCPlatformPayload* OCPlatformPayloadCreateAsOwner(OCPlatformInfo* platformInfo);
+OC_EXPORT void OCPlatformInfoDestroy(OCPlatformInfo *info);
+OC_EXPORT void OCPlatformPayloadDestroy(OCPlatformPayload* payload);
 
 // Presence Payload
-OCPresencePayload* OCPresencePayloadCreate(uint32_t seqNum, uint32_t maxAge,
+OC_EXPORT OCPresencePayload* OCPresencePayloadCreate(uint32_t seqNum, uint32_t maxAge,
         OCPresenceTrigger trigger, const char* resourceType);
-void OCPresencePayloadDestroy(OCPresencePayload* payload);
+OC_EXPORT void OCPresencePayloadDestroy(OCPresencePayload* payload);
 
 // Helper API
-OCStringLL* CloneOCStringLL (OCStringLL* ll);
-void OCFreeOCStringLL(OCStringLL* ll);
+OC_EXPORT OCStringLL* CloneOCStringLL (OCStringLL* ll);
+OC_EXPORT void OCFreeOCStringLL(OCStringLL* ll);
+
+/**
+ * This function creates a list from a string (with separated contents if several)
+ * @param text         single string or CSV text fields
+ * @return newly allocated linked list
+ * @note separator is ',' (according to rfc4180, ';' is not valid)
+ **/
+OC_EXPORT OCStringLL* OCCreateOCStringLL(const char* text);
+
+/**
+ * This function creates a string from a list (with separated contents if several)
+ * @param ll           Pointer to list
+ * @return newly allocated string
+ * @note separator is ',' (according to rfc4180)
+ **/
+OC_EXPORT char* OCCreateString(const OCStringLL* ll);
 
 #ifdef __cplusplus
 }
index 9eeae7e..72325a2 100644 (file)
@@ -52,7 +52,7 @@ extern "C" {
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags);
+OC_EXPORT OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags);
 
 /**
  * This function Initializes the OC Stack.  Must be called prior to starting the stack.
@@ -63,7 +63,7 @@ OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlag
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode);
+OC_EXPORT OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode);
 
 #ifdef RA_ADAPTER
 /**
@@ -85,7 +85,7 @@ OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo);
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCStop();
+OC_EXPORT OCStackResult OCStop();
 
 /**
  * This function starts receiving the multicast traffic. This can be only called
@@ -112,7 +112,7 @@ OCStackResult OCStopMulticastServer();
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCProcess();
+OC_EXPORT OCStackResult OCProcess();
 
 /**
  * This function discovers or Perform requests on a specified resource
@@ -147,16 +147,16 @@ OCStackResult OCProcess();
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCDoResource(OCDoHandle *handle,
-                            OCMethod method,
-                            const char *requestUri,
-                            const OCDevAddr *destination,
-                            OCPayload* payload,
-                            OCConnectivityType connectivityType,
-                            OCQualityOfService qos,
-                            OCCallbackData *cbData,
-                            OCHeaderOption *options,
-                            uint8_t numOptions);
+OC_EXPORT OCStackResult OCDoResource(OCDoHandle *handle,
+                                     OCMethod method,
+                                     const char *requestUri,
+                                     const OCDevAddr *destination,
+                                     OCPayload* payload,
+                                     OCConnectivityType connectivityType,
+                                     OCQualityOfService qos,
+                                     OCCallbackData *cbData,
+                                     OCHeaderOption *options,
+                                     uint8_t numOptions);
 /**
  * This function cancels a request associated with a specific @ref OCDoResource invocation.
  *
@@ -168,8 +168,10 @@ OCStackResult OCDoResource(OCDoHandle *handle,
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
-        uint8_t numOptions);
+OC_EXPORT OCStackResult OCCancel(OCDoHandle handle,
+                                 OCQualityOfService qos,
+                                 OCHeaderOption * options,
+                                 uint8_t numOptions);
 
 /**
  * Register Persistent storage callback.
@@ -179,7 +181,7 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
  *     OC_STACK_OK                    No errors; Success.
  *     OC_STACK_INVALID_PARAM         Invalid parameter.
  */
-OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler);
+OC_EXPORT OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler);
 
 #ifdef WITH_PRESENCE
 /**
@@ -198,7 +200,7 @@ OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistent
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCStartPresence(const uint32_t ttl);
+OC_EXPORT OCStackResult OCStartPresence(const uint32_t ttl);
 
 /**
  * When operating in OCServer or OCClientServer mode, this API will stop sending
@@ -212,7 +214,7 @@ OCStackResult OCStartPresence(const uint32_t ttl);
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 
-OCStackResult OCStopPresence();
+OC_EXPORT OCStackResult OCStopPresence();
 #endif
 
 
@@ -226,19 +228,25 @@ OCStackResult OCStopPresence();
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler, void* callbackParameter);
+OC_EXPORT OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler, void* callbackParameter);
 
 /**
  * This function sets device information.
  *
- * @param deviceInfo   Structure passed by the server application containing the device information.
+ * Upon call to OCInit, the default Device Type (i.e. "rt") has already been set to the default
+ * Device Type "oic.wk.d". You do not have to specify "oic.wk.d" in the OCDeviceInfo.types linked
+ * list. The default Device Type is mandatory and always specified by this Device as the first
+ * Device Type.
+ *
+ * @param deviceInfo   Structure passed by the server application containing the device
+ *                     information.
  *
  * @return
  *     ::OC_STACK_OK               no errors.
  *     ::OC_STACK_INVALID_PARAM    invalid parameter.
  *     ::OC_STACK_ERROR            stack process error.
  */
-OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo);
+OC_EXPORT OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo);
 
 /**
  * This function sets platform information.
@@ -252,7 +260,7 @@ OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo);
  *     ::OC_STACK_INVALID_PARAM    invalid parameter.
  *     ::OC_STACK_ERROR            stack process error.
  */
-OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo);
+OC_EXPORT OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo);
 
 /**
  * This function creates a resource.
@@ -271,13 +279,13 @@ OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo);
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCCreateResource(OCResourceHandle *handle,
-                               const char *resourceTypeName,
-                               const char *resourceInterfaceName,
-                               const char *uri,
-                               OCEntityHandler entityHandler,
-                               void* callbackParam,
-                               uint8_t resourceProperties);
+OC_EXPORT OCStackResult OCCreateResource(OCResourceHandle *handle,
+                                         const char *resourceTypeName,
+                                         const char *resourceInterfaceName,
+                                         const char *uri,
+                                         OCEntityHandler entityHandler,
+                                         void* callbackParam,
+                                         uint8_t resourceProperties);
 
 
 /**
@@ -288,7 +296,7 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
+OC_EXPORT OCStackResult OCBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
 
 /**
  * This function removes a resource from a collection resource.
@@ -298,7 +306,7 @@ OCStackResult OCBindResource(OCResourceHandle collectionHandle, OCResourceHandle
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCUnBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
+OC_EXPORT OCStackResult OCUnBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
 
 /**
  * This function binds a resource type to a resource.
@@ -308,8 +316,8 @@ OCStackResult OCUnBindResource(OCResourceHandle collectionHandle, OCResourceHand
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
-                                           const char *resourceTypeName);
+OC_EXPORT OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
+                                                     const char *resourceTypeName);
 /**
  * This function binds a resource interface to a resource.
  *
@@ -318,8 +326,8 @@ OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
-                                                const char *resourceInterfaceName);
+OC_EXPORT OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
+                                                          const char *resourceInterfaceName);
 
 /**
  * This function binds an entity handler to the resource.
@@ -330,8 +338,9 @@ OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCBindResourceHandler(OCResourceHandle handle, OCEntityHandler entityHandler,
-                                        void *callbackParameter);
+OC_EXPORT OCStackResult OCBindResourceHandler(OCResourceHandle handle,
+                                              OCEntityHandler entityHandler,
+                                              void *callbackParameter);
 
 /**
  * This function gets the number of resources that have been created in the stack.
@@ -340,7 +349,7 @@ OCStackResult OCBindResourceHandler(OCResourceHandle handle, OCEntityHandler ent
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCGetNumberOfResources(uint8_t *numResources);
+OC_EXPORT OCStackResult OCGetNumberOfResources(uint8_t *numResources);
 
 /**
  * This function gets a resource handle by index.
@@ -349,7 +358,7 @@ OCStackResult OCGetNumberOfResources(uint8_t *numResources);
  *
  * @return Found  resource handle or NULL if not found.
  */
-OCResourceHandle OCGetResourceHandle(uint8_t index);
+OC_EXPORT OCResourceHandle OCGetResourceHandle(uint8_t index);
 
 /**
  * This function deletes resource specified by handle.  Deletes resource and all
@@ -362,7 +371,7 @@ OCResourceHandle OCGetResourceHandle(uint8_t index);
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCDeleteResource(OCResourceHandle handle);
+OC_EXPORT OCStackResult OCDeleteResource(OCResourceHandle handle);
 
 /**
  * Get a string representation the server instance ID.
@@ -374,7 +383,7 @@ OCStackResult OCDeleteResource(OCResourceHandle handle);
  *
  * @return A string representation  the server instance ID.
  */
-const char* OCGetServerInstanceIDString(void);
+OC_EXPORT const char* OCGetServerInstanceIDString(void);
 
 /**
  * This function gets the URI of the resource specified by handle.
@@ -383,7 +392,7 @@ const char* OCGetServerInstanceIDString(void);
  *
  * @return URI string if resource found or NULL if not found.
  */
-const char *OCGetResourceUri(OCResourceHandle handle);
+OC_EXPORT const char *OCGetResourceUri(OCResourceHandle handle);
 
 /**
  * This function gets the properties of the resource specified by handle.
@@ -395,7 +404,7 @@ const char *OCGetResourceUri(OCResourceHandle handle);
  * @note that after a resource is created, the OC_ACTIVE property is set for the resource by the
  * stack.
  */
-OCResourceProperty OCGetResourceProperties(OCResourceHandle handle);
+OC_EXPORT OCResourceProperty OCGetResourceProperties(OCResourceHandle handle);
 
 /**
  * This function gets the number of resource types of the resource.
@@ -405,7 +414,7 @@ OCResourceProperty OCGetResourceProperties(OCResourceHandle handle);
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle, uint8_t *numResourceTypes);
+OC_EXPORT OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle, uint8_t *numResourceTypes);
 
 /**
  * This function gets name of resource type of the resource.
@@ -415,7 +424,7 @@ OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle, uint8_t *numRe
  *
  * @return Resource type name if resource found or NULL if resource not found.
  */
-const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index);
+OC_EXPORT const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index);
 
 /**
  * This function gets the number of resource interfaces of the resource.
@@ -425,7 +434,7 @@ const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index);
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
+OC_EXPORT OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
         uint8_t *numResourceInterfaces);
 
 /**
@@ -436,7 +445,7 @@ OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
  *
  * @return Resource interface name if resource found or NULL if resource not found.
  */
-const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index);
+OC_EXPORT const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index);
 
 /**
  * This function gets methods of resource interface of the resource.
@@ -446,7 +455,7 @@ const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index);
  *
  * @return Allowed methods if resource found or NULL if resource not found.
  */
-uint8_t OCGetResourceInterfaceAllowedMethods(OCResourceHandle handle, uint8_t index);
+OC_EXPORT uint8_t OCGetResourceInterfaceAllowedMethods(OCResourceHandle handle, uint8_t index);
 
 /**
  * This function gets resource handle from the collection resource by index.
@@ -456,7 +465,7 @@ uint8_t OCGetResourceInterfaceAllowedMethods(OCResourceHandle handle, uint8_t in
  *
  * @return Handle to contained resource if resource found or NULL if resource not found.
  */
-OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
+OC_EXPORT OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
         uint8_t index);
 
 /**
@@ -466,7 +475,7 @@ OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHa
  *
  * @return Entity handler if resource found or NULL resource not found.
  */
-OCEntityHandler OCGetResourceHandler(OCResourceHandle handle);
+OC_EXPORT OCEntityHandler OCGetResourceHandler(OCResourceHandle handle);
 
 /**
  * This function notify all registered observers that the resource representation has
@@ -478,7 +487,7 @@ OCEntityHandler OCGetResourceHandler(OCResourceHandle handle);
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos);
+OC_EXPORT OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos);
 
 /**
  * Notify specific observers with updated value of representation.
@@ -497,7 +506,7 @@ OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService q
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult
+OC_EXPORT OCStackResult
 OCNotifyListOfObservers (OCResourceHandle handle,
                             OCObservationId  *obsIdList,
                             uint8_t          numberOfIds,
@@ -514,7 +523,7 @@ OCNotifyListOfObservers (OCResourceHandle handle,
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCDoResponse(OCEntityHandlerResponse *response);
+OC_EXPORT OCStackResult OCDoResponse(OCEntityHandlerResponse *response);
 
 //#ifdef DIRECT_PAIRING
 /**
@@ -526,7 +535,7 @@ OCStackResult OCDoResponse(OCEntityHandlerResponse *response);
  *                    client before returning the list of devices.
  * @return OCDirectPairingDev_t pointer in case of success and NULL otherwise.
  */
-const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime);
+OC_EXPORT const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime);
 
 /**
  * The function is responsible for return of paired device list via direct-pairing. It will list
@@ -535,7 +544,7 @@ const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime);
  *
  * @return OCDirectPairingDev_t pointer in case of success and NULL otherwise.
  */
-const OCDPDev_t* OCGetDirectPairedDevices();
+OC_EXPORT const OCDPDev_t* OCGetDirectPairedDevices();
 
 /**
  * The function is responsible for establishment of direct-pairing. It will proceed mode negotiation
@@ -547,7 +556,7 @@ const OCDPDev_t* OCGetDirectPairedDevices();
  * @param[in] resultCallback Callback fucntion to event status of process.
  * @return OTM_SUCCESS in case of success and other value otherwise.
  */
-OCStackResult OCDoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
+OC_EXPORT OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
                                                      OCDirectPairingCB resultCallback);
 //#endif // DIRECT_PAIRING
 
index 2dd6224..9a32a43 100644 (file)
@@ -281,8 +281,11 @@ extern "C" {
 #ifdef RA_ADAPTER
 #define MAX_ADDR_STR_SIZE (256)
 #else
-/** Max Address could be "coap+tcp://[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx]:xxxxx" */
-#define MAX_ADDR_STR_SIZE (59)
+/** Max Address could be
+ * "coap+tcp://[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:yyy.yyy.yyy.yyy]:xxxxx"
+ * +1 for null terminator.
+ */
+#define MAX_ADDR_STR_SIZE (65)
 #endif
 
 /** Length of MAC address */
@@ -395,8 +398,8 @@ typedef enum
     /** IP & TCP adapter only.*/
     OC_IP_USE_V4       = (1 << 6),
 
-    /** internal use only.*/
-    OC_RESERVED1       = (1 << 7),   // internal use only
+    /** Multicast only.*/
+    OC_MULTICAST       = (1 << 7),
 
     /** Link-Local multicast is the default multicast scope for IPv6.
      *  These are placed here to correspond to the IPv6 multicast address bits.*/
@@ -477,7 +480,7 @@ typedef struct
     char                    addr[MAX_ADDR_STR_SIZE];
 
     /** usually zero for default interface.*/
-    uint32_t                interface;
+    uint32_t                ifindex;
 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
     char                    routeData[MAX_ADDR_STR_SIZE]; //destination GatewayID:ClientId
 #endif
@@ -670,8 +673,12 @@ typedef enum
      *  processing its requests from clients.*/
     OC_SLOW          = (1 << 3),
 
+#ifdef __WITH_DTLS__
     /** When this bit is set, the resource is a secure resource.*/
     OC_SECURE        = (1 << 4),
+#else
+    OC_SECURE        = (0),
+#endif
 
     /** When this bit is set, the resource is allowed to be discovered only
      *  if discovery request contains an explicit querystring.
@@ -849,11 +856,21 @@ typedef enum
 {
     OC_EH_OK = 0,
     OC_EH_ERROR,
-    OC_EH_RESOURCE_CREATED,
-    OC_EH_RESOURCE_DELETED,
-    OC_EH_SLOW,
-    OC_EH_FORBIDDEN,
-    OC_EH_RESOURCE_NOT_FOUND
+    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
 } OCEntityHandlerResult;
 
 /**
@@ -947,6 +964,10 @@ typedef struct
     char *deviceName;
     /** Pointer to the types.*/
     OCStringLL *types;
+    /** Pointer to the device specification version.*/
+    char *specVersion;
+    /** Pointer to the device data model versions (in CSV format).*/
+    OCStringLL *dataModelVersions;
 } OCDeviceInfo;
 
 #ifdef RA_ADAPTER
@@ -1194,10 +1215,10 @@ typedef struct
     char *uri;
 
     /** Resource Type */
-    char *type;
+    OCStringLL *type;
 
     /** Interface */
-    OCStringLL *interface;
+    OCStringLL *iface;
 
     /** This structure holds the old /oic/res response. */
     OCResourcePayload *resources;
@@ -1235,7 +1256,7 @@ typedef struct
     char *sid;
     char* deviceName;
     char* specVersion;
-    char* dataModelVersion;
+    OCStringLL *dataModelVersions;
     OCStringLL *interfaces;
     OCStringLL *types;
 } OCDevicePayload;
@@ -1245,7 +1266,7 @@ typedef struct
     OCPayload base;
     char* uri;
     OCPlatformInfo info;
-    char* rt;
+    OCStringLL* rt;
     OCStringLL* interfaces;
 } OCPlatformPayload;
 
@@ -1300,6 +1321,9 @@ typedef struct
     /** Pointer to the array of the received vendor specific header options.*/
     OCHeaderOption * rcvdVendorSpecificHeaderOptions;
 
+    /** Message id.*/
+    uint16_t messageID;
+
     /** the payload from the request PDU.*/
     OCPayload *payload;
 
@@ -1486,11 +1510,12 @@ typedef OCEntityHandlerResult (*OCDeviceEntityHandler)
 /**
  * Callback function definition of direct-pairing
  *
+ * @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'
  *                                   if D2D pairing is success without error
  */
-typedef void (*OCDirectPairingCB)(OCDPDev_t *peer, OCStackResult result);
+typedef void (*OCDirectPairingCB)(void *ctx, OCDPDev_t *peer, OCStackResult result);
 //#endif // DIRECT_PAIRING
 
 #ifdef __cplusplus
index b695d89..d04b9cd 100644 (file)
@@ -46,10 +46,10 @@ extern "C"
 #ifdef TB_LOG
     #define OIC_LOG_PAYLOAD(level, payload) OCPayloadLog((level),(payload))
     #define UUID_SIZE (16)
-const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
-OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
+OC_EXPORT const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
+OC_EXPORT OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
 
-static inline void OCPayloadLogRep(LogLevel level, OCRepPayload* payload)
+INLINE_API void OCPayloadLogRep(LogLevel level, OCRepPayload* payload)
 {
     OIC_LOG(level, (PL_TAG), "Payload Type: Representation");
     OCRepPayload* rep = payload;
@@ -164,7 +164,7 @@ static inline void OCPayloadLogRep(LogLevel level, OCRepPayload* payload)
 
 }
 
-static inline void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* payload)
+INLINE_API void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* payload)
 {
     OIC_LOG(level, PL_TAG, "Payload Type: Discovery");
     int i = 1;
@@ -189,10 +189,13 @@ static inline void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* pay
     }
     if (payload->type)
     {
-        OIC_LOG_V(level, PL_TAG, "\tResource Type: %s", payload->type);
+        for (OCStringLL *strll = payload->type; strll; strll = strll->next)
+        {
+            OIC_LOG_V(level, PL_TAG, "\tResource Type: %s", strll->value);
+        }
     }
     OIC_LOG(level, PL_TAG, "\tInterface:");
-    for (OCStringLL *itf = payload->interface; itf; itf = itf->next)
+    for (OCStringLL *itf = payload->iface; itf; itf = itf->next)
     {
         OIC_LOG_V(level, PL_TAG, "\t\t%s", itf->value);
     }
@@ -227,13 +230,20 @@ static inline void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* pay
     }
 }
 
-static inline void OCPayloadLogDevice(LogLevel level, OCDevicePayload* payload)
+INLINE_API void OCPayloadLogDevice(LogLevel level, OCDevicePayload* payload)
 {
     OIC_LOG(level, PL_TAG, "Payload Type: Device");
     OIC_LOG_V(level, PL_TAG, "\tSID:%s", payload->sid);
     OIC_LOG_V(level, PL_TAG, "\tDevice Name:%s", payload->deviceName);
-    OIC_LOG_V(level, PL_TAG, "\tSpec Version%s", payload->specVersion);
-    OIC_LOG_V(level, PL_TAG, "\tData Model Version:%s", payload->dataModelVersion);
+    OIC_LOG_V(level, PL_TAG, "\tSpec Version:%s", payload->specVersion);
+    if (payload->dataModelVersions)
+    {
+        OIC_LOG(level, PL_TAG, "\tData Model Version:");
+        for (OCStringLL *strll = payload->dataModelVersions; strll; strll = strll->next)
+        {
+            OIC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
+        }
+    }
     if (payload->types)
     {
         OIC_LOG(level, PL_TAG, "\tResource Type:");
@@ -252,7 +262,7 @@ static inline void OCPayloadLogDevice(LogLevel level, OCDevicePayload* payload)
     }
 }
 
-static inline void OCPayloadLogPlatform(LogLevel level, OCPlatformPayload* payload)
+INLINE_API void OCPayloadLogPlatform(LogLevel level, OCPlatformPayload* payload)
 {
     OIC_LOG(level, PL_TAG, "Payload Type: Platform");
     OIC_LOG_V(level, PL_TAG, "\tURI:%s", payload->uri);
@@ -271,7 +281,10 @@ static inline void OCPayloadLogPlatform(LogLevel level, OCPlatformPayload* paylo
     if (payload->rt)
     {
         OIC_LOG(level, PL_TAG, "\tResource Types:");
-        OIC_LOG_V(level, PL_TAG, "\t\t%s", payload->rt);
+        for (OCStringLL *strll = payload->rt; strll; strll = strll->next)
+        {
+            OIC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
+        }
     }
     if (payload->interfaces)
     {
@@ -283,7 +296,7 @@ static inline void OCPayloadLogPlatform(LogLevel level, OCPlatformPayload* paylo
     }
 }
 
-static inline void OCPayloadLogPresence(LogLevel level, OCPresencePayload* payload)
+INLINE_API void OCPayloadLogPresence(LogLevel level, OCPresencePayload* payload)
 {
     OIC_LOG(level, PL_TAG, "Payload Type: Presence");
     OIC_LOG_V(level, PL_TAG, "\tSequence Number:%u", payload->sequenceNumber);
@@ -292,13 +305,13 @@ static inline void OCPayloadLogPresence(LogLevel level, OCPresencePayload* paylo
     OIC_LOG_V(level, PL_TAG, "\tResource Type:%s", payload->resourceType);
 }
 
-static inline void OCPayloadLogSecurity(LogLevel level, OCSecurityPayload* payload)
+INLINE_API void OCPayloadLogSecurity(LogLevel level, OCSecurityPayload* payload)
 {
     OIC_LOG(level, PL_TAG, "Payload Type: Security");
     OIC_LOG_V(level, PL_TAG, "\tSecurity Data: %s", payload->securityData);
 }
 
-static inline void OCRDPayloadLog(const LogLevel level, const OCRDPayload *payload)
+INLINE_API void OCRDPayloadLog(const LogLevel level, const OCRDPayload *payload)
 {
     if (!payload)
     {
@@ -321,7 +334,7 @@ static inline void OCRDPayloadLog(const LogLevel level, const OCRDPayload *paylo
     }
 }
 
-static inline void OCPayloadLog(LogLevel level, OCPayload* payload)
+INLINE_API void OCPayloadLog(LogLevel level, OCPayload* payload)
 {
     if(!payload)
     {
index 17c6417..82da858 100644 (file)
@@ -165,7 +165,7 @@ void OCDiscoveryCollectionPayloadDestroy(OCDiscoveryPayload* payload);
  * @param level LogLevel for the print.
  * @param tags Structure of the tags payload.
  */
-void OCTagsLog(const LogLevel level, const OCTagsPayload *tags);
+OC_EXPORT void OCTagsLog(const LogLevel level, const OCTagsPayload *tags);
 
 /**
  * Prints links payload.
@@ -173,7 +173,7 @@ void OCTagsLog(const LogLevel level, const OCTagsPayload *tags);
  * @param level LogLevel for the print.
  * @param tags Structure of the links payload.
  */
-void OCLinksLog(const LogLevel level, const OCLinksPayload *links);
+OC_EXPORT void OCLinksLog(const LogLevel level, const OCLinksPayload *links);
 
 #ifdef __cplusplus
 }
index fe69612..5984b17 100644 (file)
@@ -29,21 +29,26 @@ samples_env.PrependUnique(CPPPATH = [
                '../../../../logger/include',
                '../../../../stack/include',
                '../../../../../../extlibs/cjson',
+               '../../../../../../extlibs/boost/boost',
                '../../../../../oc_logger/include',
                '../../../../../connectivity/lib/libcoap-4.1.1'
                ])
 
-samples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+cc = env.get('CC')
+if cc in ['gcc']:
+       samples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+       samples_env.AppendUnique(LIBS=['-lpthread'])
 samples_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
-samples_env.AppendUnique(LIBS = ['-lpthread' ])
 samples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 
-if target_os in ['darwin', 'ios']:
-       samples_env.PrependUnique(LIBS = ['m','octbstack', 'ocsrm', 'connectivity_abstraction','coap' ])
-elif target_os not in ['arduino']:
-       samples_env.PrependUnique(LIBS = ['m', 'octbstack', 'ocsrm', 'connectivity_abstraction', 'coap'])
+samples_env.PrependUnique(LIBS = ['octbstack', 'ocsrm', 'connectivity_abstraction', 'coap'])
+
+if target_os not in ['arduino', 'windows', 'darwin', 'ios', 'msys_nt']:
        samples_env.AppendUnique(LIBS = ['rt'])
 
+if target_os not in ['windows']:
+       samples_env.PrependUnique(LIBS = ['m'])
+
 if env.get('SECURED') == '1':
     samples_env.AppendUnique(LIBS = ['tinydtls'])
 
index 3ebf005..cd47011 100644 (file)
@@ -21,6 +21,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <ocstack.h>
+#include <getopt.h>
 
 const char *getResult(OCStackResult result)
 {
diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/common.h b/resource/csdk/stack/samples/linux/SimpleClientServer/common.h
new file mode 100644 (file)
index 0000000..36a7456
--- /dev/null
@@ -0,0 +1,7 @@
+#ifndef COMMON_H_
+#define COMMON_H_
+
+const char *getResult(OCStackResult result);
+void StripNewLineChar(char* str);
+
+#endif
index 23053e7..123f969 100644 (file)
 #include <stdlib.h>
 #include <string.h>
 #include <signal.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
 #include <iostream>
 #include <sstream>
+#include <getopt.h>
 #include "ocstack.h"
 #include "logger.h"
 #include "occlient.h"
 #include "ocpayload.h"
 #include "payload_logging.h"
+#include "common.h"
+#include "platform_features.h"
 
 #ifdef ROUTING_GATEWAY
 /**
@@ -58,8 +66,6 @@ static OCDevAddr serverAddr;
 static char discoveryAddr[100];
 static std::string coapServerResource = "/a/light";
 
-void StripNewLineChar(char* str);
-
 #ifdef WITH_PRESENCE
 // The handle for observe registration
 OCDoHandle gPresenceHandle;
index 61622eb..988ce35 100644 (file)
 #include <stdlib.h>
 #include <string.h>
 #include <signal.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
 #include <stdint.h>
 #include <sstream>
 #include <iostream>
+#include <getopt.h>
 
 #include "ocstack.h"
 #include "logger.h"
@@ -33,6 +39,7 @@
 #include "payload_logging.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
+#include "common.h"
 
 #define MAX_IP_ADDR_ST_SZ  16 //string size of "155.255.255.255" (15 + 1)
 #define MAX_PORT_ST_SZ  6     //string size of "65535" (5 + 1)
index fee8870..f13c6bc 100644 (file)
 #include <stdlib.h>
 #include <string.h>
 #include <signal.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
 #include <ocstack.h>
 #include <iostream>
 #include <sstream>
+#include <getopt.h>
 #include "ocpayload.h"
 #include "payload_logging.h"
 #include "logger.h"
-const char *getResult(OCStackResult result);
+#include "common.h"
 std::string getQueryStrForGetPut();
 
 #define TAG ("occlient")
index 572b9e3..d15fdd4 100644 (file)
 #include <stdlib.h>
 #include <string.h>
 #include <signal.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
 #include <iostream>
 #include <sstream>
+#include <getopt.h>
 #include "ocstack.h"
 #include "logger.h"
 #include "occlientslow.h"
 #include "oic_string.h"
 #include "ocpayload.h"
 #include "payload_logging.h"
+#include "common.h"
 
 // Tracking user input
 static int UnicastDiscovery = 0;
@@ -41,10 +48,9 @@ static std::string coapServerResource = "/a/led";
 
 //The following variable determines the interface protocol (IP, etc)
 //to be used for sending unicast messages. Default set to IP.
-static OCConnectivityType AdapterType = CT_ADAPTER_IP;
+static OCConnectivityType adapterType = CT_ADAPTER_IP;
 static OCDevAddr endpoint;
 static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res";
-void StripNewLineChar(char* str);
 
 int gQuitFlag = 0;
 
@@ -99,7 +105,7 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
 
     ret = OCDoResource(NULL, method, query.str().c_str(), dest,
             (method == OC_REST_PUT) ? putPayload() : NULL,
-            AdapterType, qos, &cbData, options, numOptions);
+            adapterType, qos, &cbData, options, numOptions);
 
     if (ret != OC_STACK_OK)
     {
@@ -292,12 +298,12 @@ int main(int argc, char* argv[])
 
     if(ConnectivityType == CT_ADAPTER_DEFAULT || ConnectivityType == CT_IP)
     {
-        AdapterType = CT_ADAPTER_IP;
+        adapterType = CT_ADAPTER_IP;
     }
     else
     {
         OIC_LOG(INFO, TAG, "Default Connectivity type selected...");
-        AdapterType = CT_ADAPTER_IP;
+        adapterType = CT_ADAPTER_IP;
     }
 
     InitDiscovery();
index c3a7059..39627df 100644 (file)
@@ -30,6 +30,7 @@
 #include "ocpayload.h"
 #include "payload_logging.h"
 #include "ocremoteaccessclient.h"
+#include "common.h"
 
 #define SET_BUT_NOT_USED(x) (void) x
 // Tracking user input
@@ -43,7 +44,6 @@ static std::string coapServerResource = "/a/light";
 static OCDevAddr responseAddr;
 //Use ipv4addr for both InitDiscovery and InitPlatformOrDeviceDiscovery
 char remoteServerJabberID[MAX_ADDR_STR_SIZE];
-void StripNewLineChar(char* str);
 static uint16_t maxNotification = 15;
 
 // The handle for the observe registration
index cc5e968..970565a 100644 (file)
 #include <string.h>
 #include <string>
 #include <stdlib.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
 #include <signal.h>
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
+#endif
 #include <array>
+#include "oic_malloc.h"
+#include <getopt.h>
 #include "ocstack.h"
 #include "logger.h"
 #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
@@ -74,6 +85,8 @@ const char *platformVersion = "myPlatformVersion";
 const char *supportUrl = "mySupportUrl";
 const char *version = "myVersion";
 const char *systemTime = "2015-05-15T11.04";
+const char *specVersion = "myDeviceSpecVersion";
+const char *dataModelVersions = "myDeviceModelVersions";
 
 // Entity handler should check for resourceTypeName and ResourceInterface in order to GET
 // the existence of a known resource
@@ -662,8 +675,7 @@ void *ChangeLightRepresentation (void *param)
     OCStackResult result = OC_STACK_ERROR;
 
     uint8_t j = 0;
-    uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2;
-    OCObservationId obsNotify[numNotifies];
+    OCObservationId obsNotify[(SAMPLE_MAX_NUM_OBSERVATIONS)/2];
 
     while (!gQuitFlag)
     {
@@ -814,6 +826,8 @@ void DeletePlatformInfo()
 void DeleteDeviceInfo()
 {
     free (deviceInfo.deviceName);
+    free (deviceInfo.specVersion);
+    OCFreeOCStringLL (deviceInfo.dataModelVersions);
 }
 
 bool DuplicateString(char** targetString, const char* sourceString)
@@ -917,12 +931,22 @@ OCStackResult SetPlatformInfo(const char* platformID, const char *manufacturerNa
     return OC_STACK_ERROR;
 }
 
-OCStackResult SetDeviceInfo(const char* deviceName)
+OCStackResult SetDeviceInfo(const char* deviceName, const char* specVersion, const char* dataModelVersions)
 {
     if(!DuplicateString(&deviceInfo.deviceName, deviceName))
     {
         return OC_STACK_ERROR;
     }
+    if(!DuplicateString(&deviceInfo.specVersion, specVersion))
+    {
+        return OC_STACK_ERROR;
+    }
+    OCFreeOCStringLL(deviceInfo.dataModelVersions);
+    deviceInfo.dataModelVersions = OCCreateOCStringLL(dataModelVersions);
+    if (!deviceInfo.dataModelVersions)
+    {
+        return OC_STACK_ERROR;
+    }
     return OC_STACK_OK;
 }
 
@@ -1043,7 +1067,7 @@ int main(int argc, char* argv[])
         exit (EXIT_FAILURE);
     }
 
-    registrationResult = SetDeviceInfo(deviceName);
+    registrationResult = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
 
     if (registrationResult != OC_STACK_OK)
     {
@@ -1101,12 +1125,16 @@ int main(int argc, char* argv[])
 
     if (observeThreadStarted)
     {
+#ifdef HAVE_PTHREAD_H
         pthread_cancel(threadId_observe);
         pthread_join(threadId_observe, NULL);
+#endif
     }
 
+#ifdef HAVE_PTHREAD_H
     pthread_cancel(threadId_presence);
     pthread_join(threadId_presence, NULL);
+#endif
 
     OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
 
index 9c4aef5..84d902c 100644 (file)
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
 #include <signal.h>
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
+#endif
 #include "ocstack.h"
 #include "logger.h"
 #include "ocserverbasicops.h"
index 792b7d2..b5408d0 100644 (file)
 #include <string.h>
 #include <string>
 #include <stdlib.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
 #include <signal.h>
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
+#endif
 #include <ocstack.h>
 #include <logger.h>
+#include <getopt.h>
 #include "ocpayload.h"
-
-const char *getResult(OCStackResult result);
+#include "common.h"
+#include "platform_features.h"
 
 #define TAG PCF("ocservercontainer")
 
@@ -542,8 +550,10 @@ int main(int argc, char* argv[])
     /*
      * Cancel the light thread and wait for it to terminate
      */
+#ifdef HAVE_PTHREAD_H
     pthread_cancel(threadId);
     pthread_join(threadId, NULL);
+#endif
 
     OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
 
index e56e144..5f0ba4b 100644 (file)
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
 #include <signal.h>
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
+#endif
+#include <boost/config.hpp>
 #include <list>
 #include "ocstack.h"
 #include "oic_malloc.h"
 volatile sig_atomic_t gQuitFlag = 0;
 
 static std::list<OCEntityHandlerRequest *> gRequestList;
-static constexpr unsigned int SLOW_RESPONSE_DELAY_SEC = 5;
+BOOST_STATIC_CONSTEXPR unsigned int SLOW_RESPONSE_DELAY_SEC = 5;
 
 static LEDResource LED;
 
-static constexpr unsigned int SAMPLE_MAX_NUM_POST_INSTANCE = 2;
+BOOST_STATIC_CONSTEXPR unsigned int SAMPLE_MAX_NUM_POST_INSTANCE = 2;
 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
 
 //char *gResourceUri= const_cast<char *>("/a/led");
@@ -187,6 +197,21 @@ OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest
     return copyOfRequest;
 }
 
+#if !defined(SIGALRM)
+void AlarmHandler(int sig);
+int WINAPI AlarmThread(void *seconds)
+{
+    sleep((unsigned int)seconds);
+    AlarmHandler(0);
+    return 0;
+}
+
+void alarm(unsigned int seconds)
+{
+    CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)AlarmThread, (void*)seconds, 0, NULL);
+}
+#endif
+
 OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
         OCEntityHandlerRequest *entityHandlerRequest, void* /*callbackParam*/)
 {
@@ -246,7 +271,9 @@ void handleSigInt(int signum)
 // slow response when fired
 void AlarmHandler(int sig)
 {
+#ifdef SIGALRM
     if (sig == SIGALRM)
+#endif
     {
         OIC_LOG (INFO, TAG, "Server starting slow response");
         if (gRequestList.empty())
@@ -299,8 +326,10 @@ int main(int /*argc*/, char** /*argv[]*/)
     // Declare and create the example resource: LED
     createLEDResource(gResourceUri, &LED, false, 42);
 
+#ifdef SIGALRM
     // Initialize slow response alarm
     signal(SIGALRM, AlarmHandler);
+#endif
 
     // Break from loop with Ctrl-C
     OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
index 3cd3cb4..a3c66af 100644 (file)
@@ -33,20 +33,23 @@ samples_env.PrependUnique(CPPPATH = [
                ])
 
 target_os = env.get('TARGET_OS')
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
        samples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
 
        # Note: 'pthread' is in libc for android.
        if target_os != 'android':
                samples_env.AppendUnique(LIBS = ['-lpthread'])
+       samples_env.Append(LINKFLAGS = ['-Wl,--no-as-needed'])
 
 samples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-samples_env.PrependUnique(LIBS = ['octbstack', 'm', 'connectivity_abstraction', 'coap'])
+if target_os in ['windows', 'msys_nt']:
+       samples_env.PrependUnique(LIBS = ['ocsrm', 'ws2_32', 'iphlpapi'])
+else:
+       samples_env.PrependUnique(LIBS = ['m'])
+samples_env.PrependUnique(LIBS = ['octbstack', 'connectivity_abstraction', 'coap'])
 if env.get('SECURED') == '1':
     samples_env.AppendUnique(LIBS = ['tinydtls'])
 
-samples_env.Append(LINKFLAGS = ['-Wl,--no-as-needed'])
-
 if target_os == 'android':
        samples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
        samples_env.AppendUnique(LIBS = ['gnustl_shared'])
index 4a6b14e..4d0fdf0 100644 (file)
@@ -3,9 +3,17 @@
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 #include <signal.h>
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
+#endif
+#include "platform_features.h"
 #include "ocstack.h"
 #include "logger.h"
 #include "common.h"
index f531773..9eca9ab 100644 (file)
 #include <stdlib.h>
 #include <string.h>
 #include <signal.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+/** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
+#ifdef ERROR
+#undef ERROR
+#endif
+#endif
 #include <iostream>
 #include <sstream>
+#include <getopt.h>
+#include "platform_features.h"
 #include "ocstack.h"
 #include "logger.h"
 #include "occlientbasicops.h"
@@ -52,7 +63,8 @@ static OCConnectivityType ocConnType;
 //of other devices which the client trusts
 static char CRED_FILE_DEVOWNER[] = "oic_svr_db_client_devowner.dat";
 static char CRED_FILE_NONDEVOWNER[] = "oic_svr_db_client_nondevowner.dat";
-
+const char * OIC_RSRC_DOXM_URI =  "/oic/sec/doxm";
+const char * OIC_RSRC_PSTAT_URI = "/oic/sec/pstat";
 
 int gQuitFlag = 0;
 
@@ -91,8 +103,8 @@ static void PrintUsage()
     OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
     OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
     OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
-    OIC_LOG(INFO, TAG, "-d 0 : Client as Device Owner");
-    OIC_LOG(INFO, TAG, "-d 1 : Client as Non Device Owner");
+    OIC_LOG(INFO, TAG, "-d 0 : Client as Non Device Owner");
+    OIC_LOG(INFO, TAG, "-d 1 : Client as Device Owner");
 }
 
 OCStackResult InvokeOCDoResource(std::ostringstream &query,
@@ -417,9 +429,21 @@ int parseClientResponse(OCClientResponse * clientResponse)
     {
         coapServerResource.assign(res->uri);
         OIC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
-
+        if (0 == strcmp(coapServerResource.c_str(),OIC_RSRC_DOXM_URI))
+        {
+            OIC_LOG(INFO,TAG,"Skip: doxm is secure virtual resource");
+            res = res->next;
+            continue;
+        }
+        if (0 == strcmp(coapServerResource.c_str(),OIC_RSRC_PSTAT_URI))
+        {
+            OIC_LOG(INFO,TAG,"Skip: pstat is secure virtual resource");
+            res = res->next;
+            continue;
+        }
         if (res->secure)
         {
+            OIC_LOG_V(INFO,TAG,"SECUREPORT: %d",res->port);
             endpoint.port = res->port;
             coapSecureResource = 1;
         }
index fd7d8ee..af344d3 100644 (file)
 #include <stdlib.h>\r
 #include <string.h>\r
 #include <signal.h>\r
+#ifdef HAVE_UNISTD_H\r
 #include <unistd.h>\r
+#endif\r
+#ifdef HAVE_PTHREAD_H\r
 #include <pthread.h>\r
+#endif\r
 #include <iostream>\r
 #include <sstream>\r
+#if defined(HAVE_WINDOWS_H)\r
+#include <windows.h>\r
+/** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */\r
+#ifdef ERROR\r
+#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
@@ -270,10 +282,11 @@ OCStackApplicationResult discoveryReqCB(void*, OCDoHandle,
 }\r
 \r
 // This is a function called back when direct-pairing status is changed\r
-void pairingReqCB(OCDPDev_t* peer, OCStackResult result)\r
+void pairingReqCB(void *ctx, OCDPDev_t* peer, OCStackResult result)\r
 {\r
     OIC_LOG(INFO, TAG, "Callback Context for Direct-Pairing establishment\n");\r
 \r
+    (void) ctx;\r
     if (OC_STACK_OK == result)\r
     {\r
         OIC_LOG_V(INFO, TAG,\r
@@ -359,7 +372,7 @@ OCStackResult DoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber)
 \r
     // start direct pairing\r
     OIC_LOG(INFO, TAG, "   Start Direct Pairing..");\r
-    if(OC_STACK_OK != OCDoDirectPairing(peer, pmSel, pinNumber, pairingReqCB))\r
+    if(OC_STACK_OK != OCDoDirectPairing(NULL, peer, pmSel, pinNumber, pairingReqCB))\r
     {\r
         OIC_LOG(ERROR, TAG, "OCDoDirectPairing API error");\r
         return OC_STACK_ERROR;\r
@@ -405,19 +418,19 @@ FILE* client_fopen(const char *path, const char *mode)
 \r
 void *CLInterface(void *data)\r
 {\r
-    printf(RED_BEGIN"#Ready to operation ('h' for help)#\n"COLOR_END);\r
+    printf(RED_BEGIN "#Ready to operation ('h' for help)#\n" COLOR_END);\r
 \r
     (void)data;\r
     OCStackResult ret;\r
-    char query[MAX_LINE] = {0,};\r
-    const char prompt[] = BOLD_BEGIN"IoTivity-DP#"COLOR_END" ";\r
+    char query[MAX_LINE] = {0};\r
+    const char prompt[] = BOLD_BEGIN "IoTivity-DP#" COLOR_END" ";\r
     const char* helpmsg[6] = {\r
-            GREEN_BEGIN"# h  (or help) : show help message"COLOR_END,\r
-            GREEN_BEGIN"# dd (DP device discovery) : discover Direct-Pairing devices"COLOR_END,\r
-            GREEN_BEGIN"# dp (start Direct-Pairing) : negotiate DP method & start Direct-Pairing"COLOR_END,\r
-            GREEN_BEGIN"# sd (send data) : send data to device"COLOR_END,\r
-            GREEN_BEGIN"# ll (list all device) : list all discovered/paired devices"COLOR_END,\r
-            GREEN_BEGIN"# q  (quit) : quit test"COLOR_END,\r
+            GREEN_BEGIN "# h  (or help) : show help message" COLOR_END,\r
+            GREEN_BEGIN "# dd (DP device discovery) : discover Direct-Pairing devices" COLOR_END,\r
+            GREEN_BEGIN "# dp (start Direct-Pairing) : negotiate DP method & start Direct-Pairing" COLOR_END,\r
+            GREEN_BEGIN "# sd (send data) : send data to device" COLOR_END,\r
+            GREEN_BEGIN "# ll (list all device) : list all discovered/paired devices" COLOR_END,\r
+            GREEN_BEGIN "# q  (quit) : quit test" COLOR_END,\r
         };\r
 \r
     for (size_t i=0; i<(sizeof(helpmsg)/sizeof(char*)); i++)\r
@@ -625,7 +638,12 @@ int main(void)
             return 0;\r
         }\r
 \r
+#if defined(_WIN32)\r
+        Sleep(100);\r
+#else\r
         nanosleep(&timeout, NULL);\r
+#endif // defined(_WIN32)\r
+\r
     }\r
     OIC_LOG(INFO, TAG, "Exiting occlient main loop...");\r
 \r
index 22bc674..9d83669 100644 (file)
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
 #include <signal.h>
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
+#endif
+#include "platform_features.h"
 #include "ocstack.h"
 #include "logger.h"
 #include "ocpayload.h"
index ff0932f..d077505 100644 (file)
Binary files a/resource/csdk/stack/samples/linux/secure/oic_amss_db.dat and b/resource/csdk/stack/samples/linux/secure/oic_amss_db.dat differ
index 4d958e9..4574952 100644 (file)
@@ -8,44 +8,38 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
                         },\r
                         {\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/ad",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.ad"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/amacl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.amacl"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        } ,\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
@@ -89,7 +83,7 @@
         "deviceuuid": "31393139-3139-3139-3139-313931393139",\r
         "devowneruuid": "61646D69-6E44-6576-6963-655555494430",\r
         "rowneruuid": "31393139-3139-3139-3139-313931393139",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     },\r
     "cred": {\r
         "creds": [\r
index 7dbbb0a..273f155 100644 (file)
Binary files a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_devowner.dat and b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_devowner.dat differ
index 4b19514..e2a22c3 100644 (file)
@@ -8,44 +8,38 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
                         },\r
                         {\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/ad",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.ad"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/amacl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.amacl"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        } ,\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
@@ -89,7 +83,7 @@
         "deviceuuid": "32323232-3232-3232-3232-323232323232",\r
         "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
         "rowneruuid": "32323232-3232-3232-3232-323232323232",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     },\r
     "cred": {\r
         "creds": [\r
index 43b7a1c..fe16181 100644 (file)
Binary files a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat and b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat differ
index d2e33a0..5fe9f41 100644 (file)
 {
-    "acl": {\r
-        "aclist": {\r
-            "aces": [\r
-                {\r
-                    "subjectuuid": "*",\r
-                    "resources": [\r
-                        {\r
-                            "href": "/oic/res",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/p",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/presence",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        }\r
-                    ],\r
-                    "permission": 2\r
-                },\r
-                {\r
-                    "subjectuuid": "*",\r
-                    "resources": [\r
-                        {\r
-                            "href": "/oic/sec/doxm",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/sec/pstat",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/sec/acl",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/sec/cred",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        }\r
-                    ],\r
-                    "permission": 6\r
-                }\r
-            ]\r
-        },\r
-        "rowneruuid" : "64697265-6374-7061-6972-696e67446576"\r
-    },\r
-    "pstat": {\r
-        "isop": false,\r
-        "deviceuuid": "64697265-6374-7061-6972-696e67446576",\r
-        "rowneruuid": "64697265-6374-7061-6972-696e67446576",\r
-        "cm": 2,\r
-        "tm": 0,\r
-        "om": 3,\r
-        "sm": 3\r
-        },\r
-    "doxm": {\r
-        "oxms": [0],\r
-        "oxmsel": 0,\r
-        "sct": 1,\r
-        "owned": false,\r
-        "deviceuuid": "64697265-6374-7061-6972-696e67446576",\r
-        "devowneruuid": "",\r
-        "rowneruuid": "64697265-6374-7061-6972-696e67446576",\r
-        "dpc": false\r
+    "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"]
+                        },
+                        {
+                            "href": "/oic/sec/acl",
+                            "rel": "",
+                            "rt": ["oic.r.acl"],
+                            "if": ["oic.if.baseline"]
+                        },
+                        {
+                            "href": "/oic/sec/cred",
+                            "rel": "",
+                            "rt": ["oic.r.cred"],
+                            "if": ["oic.if.baseline"]
+                        }
+                    ],
+                    "permission": 6
+                }
+            ]
+        },
+        "rowneruuid" : "64697265-6374-7061-6972-696e67446576"
+    },
+    "pstat": {
+        "isop": false,
+        "deviceuuid": "64697265-6374-7061-6972-696e67446576",
+        "rowneruuid": "64697265-6374-7061-6972-696e67446576",
+        "cm": 2,
+        "tm": 0,
+        "om": 3,
+        "sm": 3
+        },
+    "doxm": {
+        "oxms": [0],
+        "oxmsel": 0,
+        "sct": 1,
+        "owned": false,
+        "deviceuuid": "64697265-6374-7061-6972-696e67446576",
+        "devowneruuid": "",
+        "rowneruuid": "64697265-6374-7061-6972-696e67446576",
+        "x.com.samsung.dpc": false\r
     }\r
 }\r
index bbdd93e..f008c51 100644 (file)
Binary files a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_nondevowner.dat and b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_nondevowner.dat differ
index 07cc051..122cbda 100644 (file)
@@ -8,44 +8,38 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
                         },\r
                         {\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/ad",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.ad"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/amacl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.amacl"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        } ,\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
@@ -89,7 +83,7 @@
         "deviceuuid": "31393139-3139-3139-3139-313931393139",\r
         "devowneruuid": "31393139-3139-3139-3139-313931393139",\r
         "rowneruuid": "31393139-3139-3139-3139-313931393139",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     },\r
     "cred": {\r
         "creds": [\r
index 7f5457c..062f3ea 100644 (file)
Binary files a/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat and b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat differ
index 1dd7463..a49ac8c 100644 (file)
@@ -8,50 +8,38 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
                         },\r
                         {\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/ad",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.ad"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/amacl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.amacl"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        } ,\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        } ,\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
                         {\r
                             "href": "/oic/sec/cred",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.cred"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 8\r
                         {\r
                             "href": "/a/led",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.core"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
-                    "permission": 6,\r
-                    "period" : ["20150630T060000/20150630T220000", "20150630T060000/20150630T200000"],\r
-                    "recurrence" : ["FREQ=DAILY; BYDAY=MO, WE, FR", "FREQ=DAILY; BYDAY=TU, TH; UNTIL=20160630"]\r
+                    "permission": 6\r
                 },\r
                 {\r
                     "subjectuuid": "37373737-3737-3737-3737-373737373737",\r
                         {\r
                             "href": "/a/led",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.core"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
-                    "permission": 6,\r
-                    "period" : ["20150630T060000/20150630T220000"],\r
-                    "recurrence" : ["FREQ=DAILY; UNTIL=20150630"]\r
+                    "permission": 6\r
                 }\r
             ]\r
         },\r
         "deviceuuid": "31313131-3131-3131-3131-313131313131",\r
         "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
         "rowneruuid": "31313131-3131-3131-3131-313131313131",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     },\r
     "cred": {\r
         "creds": [\r
index 605683a..0e7bf17 100644 (file)
Binary files a/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat and b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat differ
index e20a126..f48fcb0 100644 (file)
@@ -9,7 +9,7 @@ print "Inside the Config SConscript"
 # Map of host os and allowed target os (host: allowed target os)
 host_target_map = {
                'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
-               'windows': ['windows', 'winrt', 'android', 'arduino', 'tizen'],
+               'windows': ['windows', 'android', 'arduino', 'tizen'],
                'darwin': ['darwin', 'ios', 'android', 'arduino'],
                }
 
@@ -18,7 +18,6 @@ os_arch_map = {
                'linux': ['x86', 'x86_64', 'arm', 'arm64'],
                'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
                'windows': ['x86', 'amd64', 'arm'],
-               'winrt': ['arm'],
                'darwin': ['i386', 'x86_64'],
                'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
                'arduino': ['avr', 'arm'],
index 31f26fe..b5fc0ca 100644 (file)
@@ -29,6 +29,7 @@
 #include <signal.h>
 #include <pthread.h>
 #include <array>
+#include "oic_malloc.h"
 #include "ocstack.h"
 #include "logger.h"
 #include "ocpayload.h"
@@ -76,6 +77,8 @@ const char *platformVersion = "myPlatformVersion";
 const char *supportUrl = "mySupportUrl";
 const char *version = "myVersion";
 const char *systemTime = "2015-05-15T11.04";
+const char *specVersion = "myDeviceSpecVersion";
+const char *dataModelVersions = "myDeviceModelVersions";
 
 // Entity handler should check for resourceTypeName and ResourceInterface in order to GET
 // the existence of a known resource
@@ -807,6 +810,8 @@ void DeletePlatformInfo()
 void DeleteDeviceInfo()
 {
     free (deviceInfo.deviceName);
+    free (deviceInfo.specVersion);
+    OCFreeOCStringLL (deviceInfo.dataModelVersions);
 }
 
 bool DuplicateString(char** targetString, const char* sourceString)
@@ -910,12 +915,22 @@ OCStackResult SetPlatformInfo(const char* platformID, const char *manufacturerNa
     return OC_STACK_ERROR;
 }
 
-OCStackResult SetDeviceInfo(const char* deviceName)
+OCStackResult SetDeviceInfo(const char* deviceName, const char* specVersion, const char* dataModelVersions)
 {
     if(!DuplicateString(&deviceInfo.deviceName, deviceName))
     {
         return OC_STACK_ERROR;
     }
+    if(!DuplicateString(&deviceInfo.specVersion, specVersion))
+    {
+        return OC_STACK_ERROR;
+    }
+    OCFreeOCStringLL(deviceInfo.dataModelVersions);
+    deviceInfo.dataModelVersions = OCCreateOCStringLL(dataModelVersions);
+    if (!deviceInfo.dataModelVersions)
+    {
+        return OC_STACK_ERROR;
+    }
     return OC_STACK_OK;
 }
 
@@ -1017,7 +1032,7 @@ int main(int argc, char* argv[])
         exit (EXIT_FAILURE);
     }
 
-    registrationResult = SetDeviceInfo(deviceName);
+    registrationResult = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
 
     if (registrationResult != OC_STACK_OK)
     {
index f719742..9fb134a 100644 (file)
@@ -2,8 +2,8 @@
 %define ROOTDIR  %{_builddir}/%{name}-%{version}
 
 Name: com-oic-ri-sample
-Version:    0.1
-Release:    1
+Version:    1.1.1
+Release:    0
 Summary: Tizen adapter interfacesample application
 URL: http://slp-source.sec.samsung.net
 Source: %{name}-%{version}.tar.gz
index 7e559c1..3c2f8da 100644 (file)
@@ -4,8 +4,8 @@
 %define DEST_LIB_DIR  %{buildroot}/%{_libdir}
 
 Name: com-oic-ri
-Version:    0.1
-Release:    1
+Version:    1.1.1
+Release:    0
 Summary: Tizen oicri application
 URL: http://slp-source.sec.samsung.net
 Source: %{name}-%{version}.tar.gz
@@ -49,7 +49,7 @@ cp -f %{ROOTDIR}/resource/csdk/connectivity/src/libconnectivity_abstraction.so %
 cp -f %{ROOTDIR}/resource/csdk/connectivity/lib/libcoap-4.1.1/libcoap.a %{buildroot}/%{_libdir}
 cp /usr/lib/libuuid.so.1 %{buildroot}%{_libdir}
 if echo %{SECURED}|grep -qi '1'; then
-       cp -f %{ROOTDIR}/extlibs/tinydtls/libtinydtls.a %{buildroot}/%{_libdir}
+       cp -f %{ROOTDIR}/out/tizen/*/*/extlibs/tinydtls/libtinydtls.a %{buildroot}/%{_libdir}
 fi
 
 cp -rf %{ROOTDIR}/resource/csdk/stack/include/ocstack.h* %{DEST_INC_DIR}/
@@ -66,6 +66,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/*/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}
 cp extlibs/tinycbor/tinycbor/src/cbor.h %{DEST_INC_DIR}
index a24efed..cc2bfb4 100644 (file)
 #include "oic_malloc.h"
 #include <string.h>
 
-#ifdef WITH_ARDUINO
-#include "Time.h"
-#else
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
+#ifdef HAVE_ARDUINO_TIME_H
+#include "Time.h"
+#endif
 #include "coap_time.h"
 
 #include "cacommon.h"
index 896621f..f3648de 100755 (executable)
@@ -49,6 +49,8 @@
 #define NUM_PARAM_IN_QUERY   2 // The expected number of parameters in a query
 #define NUM_FIELDS_IN_QUERY  2 // The expected number of fields in a query
 
+#include "platform_features.h"
+
 static OCStackResult CheckRTParamSupport(const OCResource* resource, const char* rtPtr)
 {
     if (!resource || !rtPtr)
index 636572a..2051f73 100644 (file)
@@ -155,7 +155,8 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
                                     request->numRcvdVendorSpecificHeaderOptions,
                                     request->rcvdVendorSpecificHeaderOptions,
                                     OC_OBSERVE_NO_OPTION,
-                                    0);
+                                    0,
+                                    request->coapID);
                         if (result == OC_STACK_OK)
                         {
                             ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest,
@@ -376,7 +377,7 @@ OCStackResult AddObserver (const char         *resUri,
         return OC_STACK_RESOURCE_ERROR;
     }
 
-    if (!resUri || !token || !*token)
+    if (!resUri || !token)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -446,7 +447,7 @@ ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLen
 {
     ResourceObserver *out = NULL;
 
-    if (token && *token)
+    if (token)
     {
         OIC_LOG(INFO, TAG, "Looking for token");
         OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
@@ -472,7 +473,7 @@ ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLen
 
 OCStackResult DeleteObserverUsingToken (CAToken_t token, uint8_t tokenLength)
 {
-    if (!token || !*token)
+    if (!token)
     {
         return OC_STACK_INVALID_PARAM;
     }
index 2ad55b2..115179a 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+// Required for strok_r
+#define _POSIX_C_SOURCE 200112L
 
+#include <stdio.h>
 #include "ocpayload.h"
 #include "octypes.h"
 #include <string.h>
@@ -30,6 +33,7 @@
 #include "rdpayload.h"
 
 #define TAG "OIC_RI_PAYLOAD"
+#define CSV_SEPARATOR ','
 
 static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val);
 
@@ -188,6 +192,12 @@ static void OCCopyPropertyValue (OCRepPayloadValue *dest, OCRepPayloadValue *sou
         case OCREP_PROP_STRING:
             dest->str = OICStrdup(source->str);
             break;
+        case OCREP_PROP_BYTE_STRING:
+            dest->ocByteStr.bytes = (uint8_t*)OICMalloc(source->ocByteStr.len * sizeof(uint8_t));
+            VERIFY_PARAM_NON_NULL(TAG, dest->ocByteStr.bytes, "Failed allocating memory");
+            dest->ocByteStr.len = source->ocByteStr.len;
+            memcpy(dest->ocByteStr.bytes, source->ocByteStr.bytes, dest->ocByteStr.len);
+            break;
         case OCREP_PROP_OBJECT:
             dest->obj = OCRepPayloadClone(source->obj);
             break;
@@ -198,6 +208,8 @@ static void OCCopyPropertyValue (OCRepPayloadValue *dest, OCRepPayloadValue *sou
             // Nothing to do for the trivially copyable types.
             break;
     }
+exit:
+    return;
 }
 
 static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val)
@@ -416,14 +428,14 @@ bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceTyp
     }
 }
 
-bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* interface)
+bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* iface)
 {
-    return OCRepPayloadAddInterfaceAsOwner(payload, OICStrdup(interface));
+    return OCRepPayloadAddInterfaceAsOwner(payload, OICStrdup(iface));
 }
 
-bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface)
+bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* iface)
 {
-    if (!payload || !interface)
+    if (!payload || !iface)
     {
         return false;
     }
@@ -441,7 +453,7 @@ bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface)
         {
             return false;
         }
-        cur->next->value = interface;
+        cur->next->value = iface;
         return true;
     }
     else
@@ -451,7 +463,7 @@ bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface)
         {
             return false;
         }
-        payload->interfaces->value = interface;
+        payload->interfaces->value = iface;
         return true;
     }
 }
@@ -741,7 +753,7 @@ bool OCRepPayloadSetByteStringArray(OCRepPayload* payload, const char* name,
 {
     if (!array)
     {
-        return NULL;
+        return false;
     }
 
     size_t dimTotal = calcDimTotal(dimensions);
@@ -971,7 +983,7 @@ bool OCRepPayloadGetDoubleArray(const OCRepPayload* payload, const char* name,
         return false;
     }
 
-    if (val->arr.type != OCREP_PROP_DOUBLE)
+    if (val->arr.type == OCREP_PROP_DOUBLE)
     {
         memcpy(*array, val->arr.dArray, dimTotal * sizeof(double));
     }
@@ -1273,6 +1285,94 @@ OCStringLL* CloneOCStringLL (OCStringLL* ll)
     return headOfClone;
 }
 
+OCStringLL* OCCreateOCStringLL(const char* text)
+{
+    char *token = NULL;
+    char *head = NULL;
+    char *tail = NULL;
+    char *backup  = NULL;
+    OCStringLL* result = NULL;
+    OCStringLL* iter = NULL;
+    OCStringLL* prev = NULL;
+    static const char delim[] = { CSV_SEPARATOR, '\0' };
+
+    VERIFY_PARAM_NON_NULL(TAG, text, "Invalid parameter");
+    backup = OICStrdup(text);
+    VERIFY_PARAM_NON_NULL(TAG, backup, "Failed allocating memory");
+
+    for (head = backup; ; head = NULL)
+    {
+        token = (char *) strtok_r(head, delim, &tail);
+        if (!token) break;
+        iter = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
+        VERIFY_PARAM_NON_NULL(TAG, iter, "Failed allocating memory");
+        if (!result)
+        {
+             result = iter;
+        }
+        else
+        {
+             prev->next = iter;
+        }
+        iter->value = OICStrdup(token);
+        VERIFY_PARAM_NON_NULL(TAG, iter->value, "Failed allocating memory");
+        prev = iter;
+        iter = iter->next;
+    }
+    OICFree(backup);
+    return result;
+
+exit:
+    OICFree(backup);
+    OCFreeOCStringLL(result);
+    return NULL;
+}
+
+char* OCCreateString(const OCStringLL* ll)
+{
+    char *str = NULL;
+    char *pos = NULL;
+    size_t len = 0;
+    size_t sublen = 0;
+    int count = 0;
+
+    if (!ll) return NULL;
+
+    for (const OCStringLL *it = ll; it ; it = it->next )
+    {
+        len += strlen(it->value) + 1;
+    }
+    len--; // renove trailing separator (just added above)
+    str = (char*) malloc(len + 1);
+    if (!str)
+        return NULL;
+
+    pos = str;
+    const OCStringLL *it = ll;
+    while (it)
+    {
+        sublen = strlen(it->value);
+        count = snprintf(pos, len + 1, "%s", it->value);
+        if (count<sublen)
+        {
+            free(str);
+            return NULL;
+        }
+        len-=sublen;
+        pos+=count;
+
+        it = it->next;
+        if (it)
+        {
+            *pos = CSV_SEPARATOR;
+            len--;
+            *(++pos) = '\0';
+       }
+    }
+
+    return str;
+}
+
 OCRepPayload* OCRepPayloadClone (const OCRepPayload* payload)
 {
     if (!payload)
@@ -1386,8 +1486,12 @@ OCResourcePayload* OCDiscoveryPayloadGetResource(OCDiscoveryPayload* payload, si
     return NULL;
 }
 
+#ifndef TCP_ADAPTER
+static OCResourcePayload* OCCopyResource(const OCResource* res, uint16_t securePort)
+#else
 static OCResourcePayload* OCCopyResource(const OCResource* res, uint16_t securePort,
                                          uint16_t tcpPort)
+#endif
 {
     OCResourcePayload* pl = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
     if (!pl)
@@ -1489,11 +1593,19 @@ static OCResourcePayload* OCCopyResource(const OCResource* res, uint16_t secureP
     return pl;
 }
 
+#ifndef TCP_ADAPTER
+void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
+                                   uint16_t securePort)
+{
+    OCDiscoveryPayloadAddNewResource(payload, OCCopyResource(res, securePort));
+}
+#else
 void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
                                    uint16_t securePort, uint16_t tcpPort)
 {
     OCDiscoveryPayloadAddNewResource(payload, OCCopyResource(res, securePort, tcpPort));
 }
+#endif
 
 bool OCResourcePayloadAddStringLL(OCStringLL **stringLL, const char *value)
 {
@@ -1570,9 +1682,9 @@ void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload)
     OICFree(payload->sid);
     OICFree(payload->baseURI);
     OICFree(payload->uri);
-    OICFree(payload->type);
+    OCFreeOCStringLL(payload->type);
     OICFree(payload->name);
-    OCFreeOCStringLL(payload->interface);
+    OCFreeOCStringLL(payload->iface);
     OCDiscoveryResourceDestroy(payload->resources);
     OICFree(payload);
 }
@@ -1607,8 +1719,8 @@ OCDevicePayload* OCDevicePayloadCreate(const char* sid, const char* dname,
         goto exit;
     }
 
-    payload->dataModelVersion = OICStrdup(dmVer);
-    if (dmVer && !payload->dataModelVersion)
+    payload->dataModelVersions = OCCreateOCStringLL(dmVer);
+    if (!payload->dataModelVersions || (dmVer && !payload->dataModelVersions->value))
     {
         goto exit;
     }
@@ -1639,7 +1751,7 @@ void OCDevicePayloadDestroy(OCDevicePayload* payload)
     OICFree(payload->sid);
     OICFree(payload->deviceName);
     OICFree(payload->specVersion);
-    OICFree(payload->dataModelVersion);
+    OCFreeOCStringLL(payload->dataModelVersions);
     OCFreeOCStringLL(payload->types);
     OCFreeOCStringLL(payload->interfaces);
     OICFree(payload);
@@ -1681,7 +1793,12 @@ OCPlatformPayload* OCPlatformPayloadCreateAsOwner(OCPlatformInfo* platformInfo)
         return NULL;
     }
     payload->interfaces->value = OICStrdup(OC_RSRVD_INTERFACE_READ);
-    payload->rt = OICStrdup(OC_RSRVD_RESOURCE_TYPE_PLATFORM);
+    payload->rt = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
+    if (!payload->rt)
+    {
+        return NULL;
+    }
+    payload->rt->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_PLATFORM);
     payload->info = *platformInfo;
 
     return payload;
@@ -1697,7 +1814,7 @@ OCPlatformPayload* OCPlatformPayloadCreate(const OCPlatformInfo* platformInfo)
     }
 
     payload->base.type = PAYLOAD_TYPE_PLATFORM;
-    payload->rt = OICStrdup(OC_RSRVD_RESOURCE_TYPE_PLATFORM);
+    OCResourcePayloadAddStringLL(&payload->rt, OC_RSRVD_RESOURCE_TYPE_PLATFORM);
 
     OCResourcePayloadAddStringLL(&payload->interfaces, OC_RSRVD_INTERFACE_DEFAULT);
     OCResourcePayloadAddStringLL(&payload->interfaces, OC_RSRVD_INTERFACE_READ);
@@ -1730,7 +1847,7 @@ void OCPlatformPayloadDestroy(OCPlatformPayload* payload)
     }
     OICFree(payload->uri);
     OCPlatformInfoDestroy(&payload->info);
-    OICFree(payload->rt);
+    OCFreeOCStringLL(payload->rt);
     OCFreeOCStringLL(payload->interfaces);
     OICFree(payload);
 }
index 7eee7b9..890b527 100644 (file)
@@ -38,6 +38,9 @@
 // Discovery Links Map Length.
 #define LINKS_MAP_LEN 4
 
+// Default data model versions in CVS form
+#define DEFAULT_DATA_MODEL_VERSIONS "res.1.1.0,sh.1.1.0"
+
 // Functions all return either a CborError, or a negative version of the OC_STACK return values
 static int64_t OCConvertPayloadHelper(OCPayload *payload, uint8_t *outPayload, size_t *size);
 static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload *payload, uint8_t *outPayload,
@@ -65,7 +68,7 @@ OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t*
     // TinyCbor Version 47a78569c0 or better on master is required for the re-allocation
     // strategy to work.  If you receive the following assertion error, please do a git-pull
     // from the extlibs/tinycbor/tinycbor directory
-    #define CborNeedsUpdating  (CborErrorOutOfMemory < CborErrorDataTooLarge)
+    #define CborNeedsUpdating  (((unsigned int)CborErrorOutOfMemory) < ((unsigned int)CborErrorDataTooLarge))
     OC_STATIC_ASSERT(!CborNeedsUpdating, "tinycbor needs to be updated to at least 47a78569c0");
     #undef CborNeedsUpdating
 
@@ -229,8 +232,7 @@ static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload *payload, uint8_t *o
         [                                                       // rootArray
             {                                                   // rootMap
                 "di" : UUID,                                    // device ID
-                "href": "/oic/res"
-                "rt": "oic.wk.res"
+                "rt": ["oic.wk.res"]
                 "n":"MyDevice"
                 "if":"oic.if.ll oic.if.baseline"
                 "di": "0685B960-736F-46F7-BEC0-9E6CBD61ADC1",
@@ -264,25 +266,19 @@ static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload *payload, uint8_t *o
                 sizeof(OC_RSRVD_DEVICE_NAME) - 1, payload->name);
         VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting name");
 
-        // Insert URI
-        err |= ConditionalAddTextStringToMap(&rootMap, OC_RSRVD_HREF, sizeof(OC_RSRVD_HREF) - 1,
-                payload->uri);
-        VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting href");
-
         // Insert Device ID into the root map
         err |= AddTextStringToMap(&rootMap, OC_RSRVD_DEVICE_ID, sizeof(OC_RSRVD_DEVICE_ID) - 1,
                 payload->sid);
         VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting device id");
 
         // Insert Resource Type
-        err |= ConditionalAddTextStringToMap(&rootMap, OC_RSRVD_RESOURCE_TYPE,
-                sizeof(OC_RSRVD_RESOURCE_TYPE) - 1, payload->type);
+        err |= OCStringLLJoin(&rootMap, OC_RSRVD_RESOURCE_TYPE, payload->type);
         VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting RT");
 
         // Insert interfaces
-        if (payload->interface)
+        if (payload->iface)
         {
-            err |= OCStringLLJoin(&rootMap, OC_RSRVD_INTERFACE, payload->interface);
+            err |= OCStringLLJoin(&rootMap, OC_RSRVD_INTERFACE, payload->iface);
             VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding interface types tag/value");
         }
 
@@ -341,15 +337,14 @@ static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload *payload, uint8_t *o
             err |= cbor_encode_uint(&policyMap, resource->bitmap);
             VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding bitmap value to policy map");
 
-            if (resource->secure)
-            {
-                err |= cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
-                        sizeof(OC_RSRVD_SECURE) - 1);
-                VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding secure tag to policy map");
-                err |= cbor_encode_boolean(&policyMap, OC_RESOURCE_SECURE);
-                VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding secure value to policy map");
-            }
-            if ((resource->secure && resource->port != 0) || payload->baseURI)
+            // Secure
+            err |= cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
+                    sizeof(OC_RSRVD_SECURE) - 1);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding secure tag to policy map");
+            err |= cbor_encode_boolean(&policyMap, resource->secure);
+            VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding secure value to policy map");
+
+            if (resource->secure || payload->baseURI)
             {
                 err |= cbor_encode_text_string(&policyMap, OC_RSRVD_HOSTING_PORT,
                         sizeof(OC_RSRVD_HOSTING_PORT) - 1);
@@ -397,6 +392,7 @@ static int64_t OCConvertDevicePayload(OCDevicePayload *payload, uint8_t *outPayl
     }
     int64_t err = CborNoError;
     CborEncoder encoder;
+    char *dataModelVersions = 0;
 
     cbor_encoder_init(&encoder, outPayload, *size, 0);
     CborEncoder repMap;
@@ -432,10 +428,20 @@ static int64_t OCConvertDevicePayload(OCDevicePayload *payload, uint8_t *outPayl
             sizeof(OC_RSRVD_SPEC_VERSION) - 1, payload->specVersion);
     VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding data spec version");
 
-    // Device data Model Version
+    // Device data Model Versions
+    if (payload->dataModelVersions)
+    {
+        OIC_LOG(INFO, TAG, "Payload has data model versions");
+        dataModelVersions = OCCreateString(payload->dataModelVersions);
+    }
+    else
+    {
+        dataModelVersions = OICStrdup(DEFAULT_DATA_MODEL_VERSIONS);
+    }
     err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_DATA_MODEL_VERSION,
-            sizeof(OC_RSRVD_DATA_MODEL_VERSION) - 1, payload->dataModelVersion);
-    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding data model version");
+        sizeof(OC_RSRVD_DATA_MODEL_VERSION) - 1, dataModelVersions);
+    OICFree(dataModelVersions);
+    VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding data model versions");
 
     err |= cbor_encoder_close_container(&encoder, &repMap);
     VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing device map");
@@ -514,8 +520,7 @@ static int64_t OCConvertPlatformPayload(OCPlatformPayload *payload, uint8_t *out
     // Resource type
     if (payload->rt)
     {
-        err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_RESOURCE_TYPE,
-                sizeof(OC_RSRVD_RESOURCE_TYPE) - 1, payload->rt);
+        err |= OCStringLLJoin(&repMap, OC_RSRVD_RESOURCE_TYPE, payload->rt);
         VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding resource type.");
     }
 
old mode 100755 (executable)
new mode 100644 (file)
index 6373767..ef9dc8a
@@ -35,6 +35,7 @@
 #include "ocstackinternal.h"
 #include "payload_logging.h"
 #include "rdpayload.h"
+#include "platform_features.h"
 
 #define TAG "OIC_RI_PAYLOADPARSE"
 
@@ -248,7 +249,7 @@ static OCStackResult OCParseDiscoveryPayload(OCPayload **outPayload, CborValue *
         err = cbor_value_map_find_value(&rootMap, OC_RSRVD_RESOURCE_TYPE, &curVal);
         if (cbor_value_is_valid(&curVal))
         {
-            err = cbor_value_dup_text_string(&curVal, &(out->type), &len, NULL);
+            err = OCParseStringLL(&rootMap, OC_RSRVD_RESOURCE_TYPE, &out->type);
             VERIFY_CBOR_SUCCESS(TAG, err, "to find base uri value");
         }
 
@@ -256,11 +257,11 @@ static OCStackResult OCParseDiscoveryPayload(OCPayload **outPayload, CborValue *
         err = cbor_value_map_find_value(&rootMap, OC_RSRVD_INTERFACE, &curVal);
         if (cbor_value_is_valid(&curVal))
         {
-            err =  OCParseStringLL(&rootMap, OC_RSRVD_INTERFACE, &out->interface);
+            err =  OCParseStringLL(&rootMap, OC_RSRVD_INTERFACE, &out->iface);
         }
-        if (!out->interface)
+        if (!out->iface)
         {
-            if (!OCResourcePayloadAddStringLL(&out->interface, OC_RSRVD_INTERFACE_LL))
+            if (!OCResourcePayloadAddStringLL(&out->iface, OC_RSRVD_INTERFACE_LL))
             {
                 err = CborErrorOutOfMemory;
             }
@@ -444,13 +445,17 @@ static OCStackResult OCParseDevicePayload(OCPayload **outPayload, CborValue *roo
             err = cbor_value_dup_text_string(&curVal, &out->specVersion, &len, NULL);
             VERIFY_CBOR_SUCCESS(TAG, err, "to find spec version in device payload");
         }
-        // Data Model Version
+        // Data Model Versions
         err = cbor_value_map_find_value(rootValue, OC_RSRVD_DATA_MODEL_VERSION, &curVal);
-        VERIFY_CBOR_SUCCESS(TAG, err, "to find data model ver tag");
+        VERIFY_CBOR_SUCCESS(TAG, err, "to find data model versions tag");
         if (cbor_value_is_valid(&curVal))
         {
-            err = cbor_value_dup_text_string(&curVal, &out->dataModelVersion, &len, NULL);
-            VERIFY_CBOR_SUCCESS(TAG, err, "to find data model version in device payload");
+            size_t len = 0;
+            char * str = NULL;
+            err = cbor_value_dup_text_string(&curVal, &str, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, err, "to find data model versions in device payload");
+            out->dataModelVersions = OCCreateOCStringLL(str);
+            OICFree(str);
         }
         err = cbor_value_advance(rootValue);
         VERIFY_CBOR_SUCCESS(TAG, err, "to advance device payload");
@@ -469,7 +474,7 @@ static OCStackResult OCParsePlatformPayload(OCPayload **outPayload, CborValue *r
     OCStackResult ret = OC_STACK_INVALID_PARAM;
     CborError err = CborNoError;
     OCPlatformInfo info = {0};
-    char* rt = NULL;
+    OCStringLL* rt = NULL;
     OCStringLL* interfaces = NULL;
     OCPlatformPayload* out = NULL;
 
@@ -576,7 +581,7 @@ static OCStackResult OCParsePlatformPayload(OCPayload **outPayload, CborValue *r
 
         if(cbor_value_is_valid(&repVal))
         {
-            err = cbor_value_dup_text_string(&repVal, &rt, &len, NULL);
+            err = OCParseStringLL(rootValue, OC_RSRVD_RESOURCE_TYPE, &rt);
             VERIFY_CBOR_SUCCESS(TAG, err, "Failed to find resource type in the platform payload");
         }
 
@@ -1186,17 +1191,21 @@ static OCStackResult OCParsePresencePayload(OCPayload **outPayload, CborValue *r
     if (cbor_value_is_map(rootValue))
     {
         CborValue curVal;
+        uint64_t temp = 0;
 
         // Sequence Number
         CborError err = cbor_value_map_find_value(rootValue, OC_RSRVD_NONCE, &curVal);
         VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding nonce tag");
-        err = cbor_value_get_uint64(&curVal, (uint64_t *)&payload->sequenceNumber);
+        err = cbor_value_get_uint64(&curVal, &temp);
+        payload->sequenceNumber = (uint32_t)temp;
         VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding nonce value");
 
         // Max Age
         err = cbor_value_map_find_value(rootValue, OC_RSRVD_TTL, &curVal);
         VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding ttl tag");
-        err = cbor_value_get_uint64(&curVal, (uint64_t *)&payload->maxAge);
+        temp = 0;
+        err = cbor_value_get_uint64(&curVal, &temp);
+        payload->maxAge = (uint32_t)temp;
         VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding ttl value");
 
         // Trigger
index 29dff7f..cc25c77 100755 (executable)
 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
 #define _POSIX_C_SOURCE 200112L
 
-#ifdef WITH_ARDUINO
+#ifdef WITH_STRING_H
 #include <string.h>
-#else
+#endif
+#ifdef WITH_STRINGS_H
 #include <strings.h>
 #endif
 
@@ -64,6 +65,8 @@
 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
              TAG, #arg " is NULL"); return (retVal); } }
 
+#include "platform_features.h"
+
 extern OCResource *headResource;
 static OCPlatformInfo savedPlatformInfo = {0};
 static OCDeviceInfo savedDeviceInfo = {0};
@@ -334,9 +337,11 @@ OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr,
     {
         tcpPort = 0;
     }
+    OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
+#else
+    OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
 #endif
 
-    OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
     return OC_STACK_OK;
 }
 
@@ -700,8 +705,6 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
     }
 
     OCStackResult discoveryResult = OC_STACK_ERROR;
-
-    bool bMulticast    = false;     // Was the discovery request a multicast request?
     OCPayload* payload = NULL;
 
     OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
@@ -750,13 +753,6 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
                     for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
                     {
                         bool result = false;
-                        if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
-                        {
-                            if (resourceTypeQuery && resourceMatchesRTFilter(resource, resourceTypeQuery))
-                            {
-                                result = true;
-                            }
-                        }
                         if (resource->resourceProperties & OC_DISCOVERABLE)
                         {
                             result = true;
@@ -771,8 +767,7 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
                 }
                 else
                 {
-                    if ((interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL))) ||
-                        !interfaceQuery)
+                    if (interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
                     {
                         discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
                         VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
@@ -781,11 +776,13 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
                             discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
                             VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
                         }
-                        discPayload->type = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
+                        discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
                         VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
-                        OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_LL);
-                        OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_DEFAULT);
-                        VERIFY_NON_NULL(discPayload->interface, ERROR, OC_STACK_NO_MEMORY);
+                        discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
+                        VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
+                        OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
+                        OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
+                        VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
                     }
                     bool foundResourceAtRD = false;
                     for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
@@ -868,15 +865,24 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
         }
         else
         {
-            payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
-                savedDeviceInfo.types, OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
-            if (!payload)
+            char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
+            if (!dataModelVersions)
             {
                 discoveryResult = OC_STACK_NO_MEMORY;
             }
             else
             {
-                discoveryResult = OC_STACK_OK;
+                payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
+                    savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
+                if (!payload)
+                {
+                     discoveryResult = OC_STACK_NO_MEMORY;
+                }
+                else
+                {
+                     discoveryResult = OC_STACK_OK;
+                }
+                OICFree(dataModelVersions);
             }
         }
     }
@@ -940,19 +946,19 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
         {
             SendNonPersistantDiscoveryResponse(request, resource, payload, OC_EH_OK);
         }
-        else if(bMulticast == false && (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
-               (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
+        else if(((request->devAddr.flags &  OC_MULTICAST) == false) &&
+            (request->devAddr.adapter != OC_ADAPTER_RFCOMM_BTEDR) &&
+            (request->devAddr.adapter != OC_ADAPTER_GATT_BTLE))
         {
-            OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d)  \
-                discovery request", discoveryResult, virtualUriInRequest);
+            OIC_LOG_V(ERROR, TAG, "Sending a (%d) error to (%d) discovery request",
+                discoveryResult, virtualUriInRequest);
             SendNonPersistantDiscoveryResponse(request, resource, NULL,
                 (discoveryResult == OC_STACK_NO_RESOURCE) ? OC_EH_RESOURCE_NOT_FOUND : OC_EH_ERROR);
         }
         else
         {
             // Ignoring the discovery request as per RFC 7252, Section #8.2
-            OIC_LOG(INFO, TAG, "Silently ignoring the request since device does not have \
-                any useful data to send");
+            OIC_LOG(INFO, TAG, "Silently ignoring the request since no useful data to send. ");
         }
     }
 
@@ -985,7 +991,8 @@ HandleDefaultDeviceEntityHandler (OCServerRequest *request)
                                         request->numRcvdVendorSpecificHeaderOptions,
                                         request->rcvdVendorSpecificHeaderOptions,
                                         (OCObserveAction)request->observationOption,
-                                        (OCObservationId)0);
+                                        (OCObservationId)0,
+                                        request->coapID);
     VERIFY_SUCCESS(result, OC_STACK_OK);
 
     // At this point we know for sure that defaultDeviceHandler exists
@@ -1049,7 +1056,8 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
                                         request->numRcvdVendorSpecificHeaderOptions,
                                         request->rcvdVendorSpecificHeaderOptions,
                                         (OCObserveAction)request->observationOption,
-                                        0);
+                                        0,
+                                        request->coapID);
     VERIFY_SUCCESS(result, OC_STACK_OK);
 
     if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
@@ -1096,13 +1104,13 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
         }
         else
         {
-            result = OC_STACK_OK;
-
             // The error in observeResult for the request will be used when responding to this
             // request by omitting the observation option/sequence number.
             request->observeResult = OC_STACK_ERROR;
             OIC_LOG(ERROR, TAG, "Observer Addition failed");
             ehFlag = OC_REQUEST_FLAG;
+            FindAndDeleteServerRequest(request);
+            goto exit;
         }
 
     }
@@ -1132,9 +1140,10 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
         }
         else
         {
-            result = OC_STACK_OK;
             request->observeResult = OC_STACK_ERROR;
             OIC_LOG(ERROR, TAG, "Observer Removal failed");
+            FindAndDeleteServerRequest(request);
+            goto exit;
         }
     }
     else
@@ -1183,7 +1192,8 @@ HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
                                         request->numRcvdVendorSpecificHeaderOptions,
                                         request->rcvdVendorSpecificHeaderOptions,
                                         (OCObserveAction)request->observationOption,
-                                        (OCObservationId)0);
+                                        (OCObservationId)0,
+                                        request->coapID);
     if(result == OC_STACK_OK)
     {
         result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
@@ -1340,8 +1350,11 @@ void DeleteDeviceInfo()
 
     OICFree(savedDeviceInfo.deviceName);
     OCFreeOCStringLL(savedDeviceInfo.types);
+    OICFree(savedDeviceInfo.specVersion);
+    OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
     savedDeviceInfo.deviceName = NULL;
-
+    savedDeviceInfo.specVersion = NULL;
+    savedDeviceInfo.dataModelVersions = NULL;
 }
 
 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
@@ -1363,6 +1376,50 @@ static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
             return OC_STACK_NO_MEMORY;
         }
     }
+
+    if (info.specVersion)
+    {
+        savedDeviceInfo.specVersion = OICStrdup(info.specVersion);
+        if(!savedDeviceInfo.specVersion && info.specVersion)
+        {
+            DeleteDeviceInfo();
+            return OC_STACK_NO_MEMORY;
+        }
+    }
+    else
+    {
+        savedDeviceInfo.specVersion = OICStrdup(OC_SPEC_VERSION);
+        if(!savedDeviceInfo.specVersion && OC_SPEC_VERSION)
+        {
+            DeleteDeviceInfo();
+            return OC_STACK_NO_MEMORY;
+        }
+    }
+
+    if (info.dataModelVersions)
+    {
+        savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
+        if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
+        {
+            DeleteDeviceInfo();
+            return OC_STACK_NO_MEMORY;
+        }
+    }
+    else
+    {
+        savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
+        if (!savedDeviceInfo.dataModelVersions)
+        {
+            return OC_STACK_NO_MEMORY;
+        }
+        savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
+        if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
+        {
+            DeleteDeviceInfo();
+            return OC_STACK_NO_MEMORY;
+        }
+    }
+
     return OC_STACK_OK;
 }
 
index 8263100..2b4d1b3 100644 (file)
@@ -362,7 +362,8 @@ OCStackResult FormOCEntityHandlerRequest(
         uint8_t numVendorOptions,
         OCHeaderOption * vendorOptions,
         OCObserveAction observeAction,
-        OCObservationId observeID)
+        OCObservationId observeID,
+        uint16_t messageID)
 {
     if (entityHandlerRequest)
     {
@@ -373,6 +374,7 @@ OCStackResult FormOCEntityHandlerRequest(
         entityHandlerRequest->query = queryBuf;
         entityHandlerRequest->obsInfo.action = observeAction;
         entityHandlerRequest->obsInfo.obsId = observeID;
+        entityHandlerRequest->messageID = messageID;
 
         if(payload && payloadSize)
         {
@@ -419,49 +421,67 @@ void FindAndDeleteServerRequest(OCServerRequest * serverRequest)
 
 CAResponseResult_t ConvertEHResultToCAResult (OCEntityHandlerResult result, OCMethod method)
 {
-    CAResponseResult_t caResult;
+    CAResponseResult_t caResult = CA_BAD_REQ;
 
     switch (result)
     {
-        case OC_EH_OK:
-           switch (method)
-           {
-               case OC_REST_PUT:
-               case OC_REST_POST:
-                   // This Response Code is like HTTP 204 "No Content" but only used in
-                   // response to POST and PUT requests.
-                   caResult = CA_CHANGED;
-                   break;
-               case OC_REST_GET:
-                   // This Response Code is like HTTP 200 "OK" but only used in response to
-                   // GET requests.
-                   caResult = CA_CONTENT;
-                   break;
-               default:
-                   // This should not happen but,
-                   // give it a value just in case but output an error
-                   caResult = CA_CONTENT;
-                   OIC_LOG_V(ERROR, TAG, "Unexpected OC_EH_OK return code for method [%d].", method);
-           }
+        // Successful Client Request
+        case OC_EH_RESOURCE_CREATED: // 2.01
+            if (method == OC_REST_POST || method == OC_REST_PUT)
+            {
+                caResult = CA_CREATED;
+            }
             break;
-        case OC_EH_ERROR:
-            caResult = CA_BAD_REQ;
+        case OC_EH_RESOURCE_DELETED: // 2.02
+            if (method == OC_REST_POST || method == OC_REST_DELETE)
+            {
+                caResult = CA_DELETED;
+            }
             break;
-        case OC_EH_RESOURCE_CREATED:
-            caResult = CA_CREATED;
+        case OC_EH_SLOW: // 2.05
+            caResult = CA_CONTENT;
             break;
-        case OC_EH_RESOURCE_DELETED:
-            caResult = CA_DELETED;
+        case OC_EH_OK: // 2.04/2.05
+            if (method == OC_REST_POST || method == OC_REST_PUT)
+            {
+                caResult = CA_CHANGED;
+            }
+            else if (method == OC_REST_GET)
+            {
+                caResult = CA_CONTENT;
+            }
             break;
-        case OC_EH_SLOW:
-            caResult = CA_CONTENT;
+        case OC_EH_VALID: // 2.03
+            caResult = CA_VALID;
             break;
-        case OC_EH_FORBIDDEN:
+        case OC_EH_CHANGED: // 2.04
+            caResult = CA_CHANGED;
+            break;
+        // Unsuccessful Client Request
+        case OC_EH_UNAUTHORIZED_REQ: // 4.01
             caResult = CA_UNAUTHORIZED_REQ;
             break;
-        case OC_EH_RESOURCE_NOT_FOUND:
+        case OC_EH_BAD_OPT: // 4.02
+            caResult = CA_BAD_OPT;
+            break;
+        case OC_EH_FORBIDDEN: // 4.03
+            caResult = CA_FORBIDDEN_REQ;
+            break;
+        case OC_EH_RESOURCE_NOT_FOUND: // 4.04
             caResult = CA_NOT_FOUND;
             break;
+        case OC_EH_METHOD_NOT_ALLOWED: // 4.05
+            caResult = CA_METHOD_NOT_ALLOWED;
+            break;
+        case OC_EH_NOT_ACCEPTABLE: // 4.06
+            caResult = CA_NOT_ACCEPTABLE;
+            break;
+        case OC_EH_INTERNAL_SERVER_ERROR: // 5.00
+            caResult = CA_INTERNAL_SERVER_ERROR;
+            break;
+        case OC_EH_RETRANSMIT_TIMEOUT: // 5.04
+            caResult = CA_RETRANSMIT_TIMEOUT;
+            break;
         default:
             caResult = CA_BAD_REQ;
             break;
@@ -495,6 +515,7 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
 
     CopyDevAddrToEndpoint(&serverRequest->devAddr, &responseEndpoint);
 
+    responseInfo.info.messageId = serverRequest->coapID;
     responseInfo.info.resourceUri = serverRequest->resourceUrl;
     responseInfo.result = ConvertEHResultToCAResult(ehResponse->ehResult, serverRequest->method);
 
@@ -514,6 +535,8 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
     else if(!serverRequest->notificationFlag && serverRequest->slowFlag &&
             serverRequest->qos == OC_HIGH_QOS)
     {
+        // To assign new messageId in CA.
+        responseInfo.info.messageId = 0;
         responseInfo.info.type = CA_MSG_CONFIRM;
     }
     else if(!serverRequest->notificationFlag)
@@ -526,14 +549,15 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
         responseInfo.info.type = CA_MSG_NONCONFIRM;
     }
 
-    char rspToken[CA_MAX_TOKEN_LEN + 1] = {};
+    char rspToken[CA_MAX_TOKEN_LEN + 1] = {0};
     responseInfo.info.messageId = serverRequest->coapID;
     responseInfo.info.token = (CAToken_t)rspToken;
 
     memcpy(responseInfo.info.token, serverRequest->requestToken, serverRequest->tokenLength);
     responseInfo.info.tokenLength = serverRequest->tokenLength;
 
-    if(serverRequest->observeResult == OC_STACK_OK)
+    // De-register observe option should not be included in the response header
+    if((serverRequest->observeResult == OC_STACK_OK) && (serverRequest->observationOption != OC_OBSERVE_DEREGISTER))
     {
         responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
     }
@@ -752,7 +776,6 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
                     (OCRepPayload*)newPayload);
         }
 
-
         (serverRequest->numResponses)--;
 
         if(serverRequest->numResponses == 0)
@@ -773,4 +796,3 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
 exit:
     return stackRet;
 }
-
index 709dba6..a578533 100644 (file)
 #include "directpairing.h"
 //#endif
 
-#ifdef WITH_ARDUINO
+#ifdef HAVE_ARDUINO_TIME_H
 #include "Time.h"
-#else
+#endif
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include "coap_time.h"
 #include "utlist.h"
 #include "pdu.h"
 
-#ifndef ARDUINO
+#ifdef HAVE_ARPA_INET_H
 #include <arpa/inet.h>
 #endif
 
@@ -118,7 +119,7 @@ static OCResourceHandle platformResource = {0};
 static OCResourceHandle deviceResource = {0};
 #ifdef WITH_PRESENCE
 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
-static PresenceResource presenceResource;
+static PresenceResource presenceResource = {0};
 static uint8_t PresenceTimeOutSize = 0;
 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
 #endif
@@ -133,10 +134,6 @@ void* defaultDeviceHandlerCallbackParameter = NULL;
 static const char COAP_TCP[] = "coap+tcp:";
 static const char CORESPEC[] = "core";
 
-//#ifdef DIRECT_PAIRING
-OCDirectPairingCB gDirectpairingCallback = NULL;
-//#endif
-
 //-----------------------------------------------------------------------------
 // Macros
 //-----------------------------------------------------------------------------
@@ -279,16 +276,6 @@ static void deleteAllResources();
  */
 static void incrementSequenceNumber(OCResource * resPtr);
 
-/**
- * Verify the lengths of the URI and the query separately.
- *
- * @param inputUri Input URI and query.
- * @param uriLen The length of the initial URI with query.
- * @return ::OC_STACK_OK on success, some other value upon failure.
- */
-static OCStackResult verifyUriQueryLength(const char * inputUri,
-        uint16_t uriLen);
-
 /*
  * Attempts to initialize every network interface that the CA Layer might have compiled in.
  *
@@ -451,7 +438,7 @@ void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
     out->flags = CAToOCTransportFlags(in->flags);
     OICStrcpy(out->addr, sizeof(out->addr), in->addr);
     out->port = in->port;
-    out->interface = in->interface;
+    out->ifindex = in->ifindex;
 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
     memcpy(out->routeData, in->routeData, sizeof(out->routeData));
 #endif
@@ -469,7 +456,7 @@ void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
     memcpy(out->routeData, in->routeData, sizeof(out->routeData));
 #endif
     out->port = in->port;
-    out->interface = in->interface;
+    out->ifindex = in->ifindex;
 }
 
 void FixUpClientResponse(OCClientResponse *cr)
@@ -532,7 +519,8 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat
                                                 NULL, PAYLOAD_TYPE_REPRESENTATION,
                                                 NULL, 0, 0, NULL,
                                                 OC_OBSERVE_DEREGISTER,
-                                                observer->observeId);
+                                                observer->observeId,
+                                                0);
             if(result != OC_STACK_OK)
             {
                 return result;
@@ -583,7 +571,8 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat
                                                     NULL, PAYLOAD_TYPE_REPRESENTATION,
                                                     NULL, 0, 0, NULL,
                                                     OC_OBSERVE_DEREGISTER,
-                                                    observer->observeId);
+                                                    observer->observeId,
+                                                    0);
                 if(result != OC_STACK_OK)
                 {
                     return OC_STACK_ERROR;
@@ -1163,7 +1152,7 @@ void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* resp
 
             OCClientResponse response =
                 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
-            response.sequenceNumber = OC_OBSERVE_NO_OPTION;
+            response.sequenceNumber = -1;
             CopyEndpointToDevAddr(endPoint, &response.devAddr);
             FixUpClientResponse(&response);
             response.resourceUri = responseInfo->info.resourceUri;
@@ -1854,7 +1843,7 @@ void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* reque
                                     CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
         }
     }
-    else if(requestResult != OC_STACK_OK)
+    else if(!OCResultToSuccess(requestResult))
     {
         OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
 
@@ -2241,31 +2230,6 @@ CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
     }
 }
 
-OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
-{
-    char *query;
-
-    query = strchr (inputUri, '?');
-
-    if (query != NULL)
-    {
-        if((query - inputUri) > MAX_URI_LENGTH)
-        {
-            return OC_STACK_INVALID_URI;
-        }
-
-        if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
-        {
-            return OC_STACK_INVALID_QUERY;
-        }
-    }
-    else if(uriLen > MAX_URI_LENGTH)
-    {
-        return OC_STACK_INVALID_URI;
-    }
-    return OC_STACK_OK;
-}
-
 /**
  *  A request uri consists of the following components in order:
  *                              example
@@ -2679,12 +2643,6 @@ OCStackResult OCDoResource(OCDoHandle *handle,
         requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
     }
 
-    if (result != OC_STACK_OK)
-    {
-        OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
-        goto exit;
-    }
-
     // prepare for response
 #ifdef WITH_PRESENCE
     if (method == OC_REST_PRESENCE)
@@ -3118,8 +3076,6 @@ OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
         {
             return OC_STACK_INVALID_PARAM;
         }
-        deleteResourceType(resource->rsrcType);
-        resource->rsrcType = NULL;
 
         while (type)
         {
@@ -3996,16 +3952,7 @@ const OCDPDev_t* OCGetDirectPairedDevices()
     return (const OCDPDev_t*)DPGetPairedDevices();
 }
 
-void DirectPairingCB (OCDirectPairingDev_t * peer, OCStackResult result)
-{
-    if (gDirectpairingCallback)
-    {
-        gDirectpairingCallback((OCDPDev_t*)peer, result);
-        gDirectpairingCallback = NULL;
-    }
-}
-
-OCStackResult OCDoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
+OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
                                                      OCDirectPairingCB resultCallback)
 {
     OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
@@ -4020,9 +3967,8 @@ OCStackResult OCDoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
         return OC_STACK_INVALID_CALLBACK;
     }
 
-    gDirectpairingCallback = resultCallback;
-    return DPDirectPairing((OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
-                                           pinNumber, DirectPairingCB);
+    return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
+                                           pinNumber, (OCDirectPairingResultCB)resultCallback);
 }
 //#endif // DIRECT_PAIRING
 
@@ -4180,6 +4126,8 @@ void deleteAllResources()
 #endif // WITH_PRESENCE
         pointer = temp;
     }
+    memset(&platformResource, 0, sizeof(platformResource));
+    memset(&deviceResource, 0, sizeof(deviceResource));
 
     SRMDeInitSecureResources();
 
@@ -4187,6 +4135,7 @@ void deleteAllResources()
     // Ensure that the last resource to be deleted is the presence resource. This allows for all
     // presence notification attributed to their deletion to be processed.
     deleteResource((OCResource *) presenceResource.handle);
+    memset(&presenceResource, 0, sizeof(presenceResource));
 #endif // WITH_PRESENCE
 }
 
@@ -4452,7 +4401,11 @@ void insertResourceInterface(OCResource *resource, OCResourceInterface *newInter
             previous = pointer;
             pointer = pointer->next;
         }
-        previous->next = newInterface;
+
+        if (previous)
+        {
+            previous->next = newInterface;
+        }
     }
 }
 
@@ -4664,3 +4617,17 @@ OCStackResult CAResultToOCResult(CAResult_t caResult)
             return OC_STACK_ERROR;
     }
 }
+
+bool OCResultToSuccess(OCStackResult ocResult)
+{
+    switch (ocResult)
+    {
+        case OC_STACK_OK:
+        case OC_STACK_RESOURCE_CREATED:
+        case OC_STACK_RESOURCE_DELETED:
+        case OC_STACK_CONTINUE:
+            return true;
+        default:
+            return false;
+    }
+}
index 383d66a..558f683 100755 (executable)
@@ -32,9 +32,7 @@
 #include "logger.h"
 #include "timer.h"
 
-#ifndef WITH_ARDUINO
-#include <pthread.h>
-#endif
+#include "platform_features.h"
 
 #define TAG "OIC_RI_GROUP"
 
         pointer = NULL; \
     }
 
-#ifndef WITH_ARDUINO
-pthread_mutex_t lock;
+// Mutex implementation macros
+#if defined(HAVE_PTHREAD_H)
+
+ #include <pthread.h>
+ pthread_mutex_t lock;
+ #define MUTEX_LOCK(ARG_NAME)    { pthread_mutex_lock(ARG_NAME); }
+ #define MUTEX_UNLOCK(ARG_NAME)  { pthread_mutex_unlock(ARG_NAME); }
+
+#elif defined(HAVE_WINDOWS_H)
+
+ #include <windows.h>
+ CRITICAL_SECTION lock;
+ #define MUTEX_LOCK(ARG_NAME)   { EnterCriticalSection(ARG_NAME); }
+ #define MUTEX_UNLOCK(ARG_NAME) { LeaveCriticalSection(ARG_NAME); }
+
+#elif defined(WITH_ARDUINO)
+
+ #define MUTEX_LOCK(ARG_NAME)   {  }
+ #define MUTEX_UNLOCK(ARG_NAME) {  }
+
+#else
+
+ ERROR Need mutex implementation on this platform
+
 #endif
 
 enum ACTION_TYPE
@@ -100,9 +120,7 @@ void AddScheduledResource(ScheduledResourceInfo **head,
 {
     OIC_LOG(INFO, TAG, "AddScheduledResource Entering...");
 
-#ifndef WITH_ARDUINO
-    pthread_mutex_lock(&lock);
-#endif
+    MUTEX_LOCK(&lock);
     ScheduledResourceInfo *tmp = NULL;
 
     if (*head != NULL)
@@ -119,25 +137,21 @@ void AddScheduledResource(ScheduledResourceInfo **head,
     {
         *head = add;
     }
-#ifndef WITH_ARDUINO
-    pthread_mutex_unlock(&lock);
-#endif
+    MUTEX_UNLOCK(&lock);
 }
 
 ScheduledResourceInfo* GetScheduledResource(ScheduledResourceInfo *head)
 {
     OIC_LOG(INFO, TAG, "GetScheduledResource Entering...");
 
-#ifndef WITH_ARDUINO
-    pthread_mutex_lock(&lock);
-#endif
+    MUTEX_LOCK(&lock);
 
     time_t t_now;
 
     ScheduledResourceInfo *tmp = NULL;
     tmp = head;
 
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO)
     time(&t_now);
 #else
     t_now = now();
@@ -148,11 +162,7 @@ ScheduledResourceInfo* GetScheduledResource(ScheduledResourceInfo *head)
         while (tmp)
         {
             time_t diffTm = 0;
-#ifndef WITH_ARDUINO
             diffTm = timespec_diff(tmp->time, t_now);
-#else
-            diffTm = timespec_diff(tmp->time, t_now);
-#endif
 
             if (diffTm <= (time_t) 0)
             {
@@ -165,9 +175,9 @@ ScheduledResourceInfo* GetScheduledResource(ScheduledResourceInfo *head)
     }
 
     exit:
-#ifndef WITH_ARDUINO
-    pthread_mutex_unlock(&lock);
-#endif
+
+    MUTEX_UNLOCK(&lock);
+
     if (tmp == NULL)
     {
         OIC_LOG(INFO, TAG, "Cannot Find Call Info.");
@@ -179,9 +189,8 @@ ScheduledResourceInfo* GetScheduledResourceByActionSetName(ScheduledResourceInfo
 {
     OIC_LOG(INFO, TAG, "GetScheduledResourceByActionSetName Entering...");
 
-#ifndef WITH_ARDUINO
-    pthread_mutex_lock(&lock);
-#endif
+    MUTEX_LOCK(&lock);
+
     ScheduledResourceInfo *tmp = NULL;
     tmp = head;
 
@@ -199,9 +208,9 @@ ScheduledResourceInfo* GetScheduledResourceByActionSetName(ScheduledResourceInfo
     }
 
 exit:
-#ifndef WITH_ARDUINO
-    pthread_mutex_unlock(&lock);
-#endif
+
+    MUTEX_UNLOCK(&lock);
+
     if (tmp == NULL)
     {
         OIC_LOG(INFO, TAG, "Cannot Find Call Info.");
@@ -212,17 +221,17 @@ exit:
 void RemoveScheduledResource(ScheduledResourceInfo **head,
         ScheduledResourceInfo* del)
 {
-#ifndef WITH_ARDUINO
-    pthread_mutex_lock(&lock);
-#endif
+
+    MUTEX_LOCK(&lock);
+
     OIC_LOG(INFO, TAG, "RemoveScheduledResource Entering...");
     ScheduledResourceInfo *tmp = NULL;
 
     if (del == NULL)
     {
-#ifndef WITH_ARDUINO
-    pthread_mutex_unlock(&lock);
-#endif
+
+        MUTEX_UNLOCK(&lock);
+
         return;
     }
 
@@ -244,9 +253,9 @@ void RemoveScheduledResource(ScheduledResourceInfo **head,
     }
 
     OCFREE(del)
-#ifndef WITH_ARDUINO
-    pthread_mutex_unlock(&lock);
-#endif
+
+    MUTEX_UNLOCK(&lock);
+
 }
 
 typedef struct aggregatehandleinfo
@@ -650,7 +659,7 @@ OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
     // yyyy-mm-dd hh:mm:ss d
     iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
     VARIFY_PARAM_NULL(iterToken, result, exit)
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO)
     if( 2 != sscanf(iterToken, "%ld %u", &(*set)->timesteps, &(*set)->type) )
     {
         // If the return value should be 2, the number of items in the argument. Otherwise, it fails.
@@ -1096,13 +1105,13 @@ void DoScheduledGroupAction()
         OIC_LOG(INFO, TAG, "Target ActionSet is NULL");
         goto exit;
     }
-#ifndef WITH_ARDUINO
-    pthread_mutex_lock(&lock);
-#endif
+
+    MUTEX_LOCK(&lock);
+
     DoAction(info->resource, info->actionset, info->ehRequest);
-#ifndef WITH_ARDUINO
-    pthread_mutex_unlock(&lock);
-#endif
+
+    MUTEX_UNLOCK(&lock);
+
 
     if (info->actionset->type == RECURSIVE)
     {
@@ -1117,9 +1126,7 @@ void DoScheduledGroupAction()
 
             if (info->actionset->timesteps > 0)
             {
-#ifndef WITH_ARDUINO
-                pthread_mutex_lock(&lock);
-#endif
+                MUTEX_LOCK(&lock);
                 schedule->resource = info->resource;
                 schedule->actionset = info->actionset;
                 schedule->ehRequest = info->ehRequest;
@@ -1129,9 +1136,7 @@ void DoScheduledGroupAction()
                         &DoScheduledGroupAction);
 
                 OIC_LOG(INFO, TAG, "Reregisteration.");
-#ifndef WITH_ARDUINO
-                pthread_mutex_unlock(&lock);
-#endif
+                MUTEX_UNLOCK(&lock);
                 AddScheduledResource(&scheduleResourceList, schedule);
             }
             else
@@ -1159,6 +1164,16 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
     char *doWhat = NULL;
     char *details = NULL;
 
+#if defined(_WIN32)
+    static bool initializedCriticalSection = false;
+
+    if(false == initializedCriticalSection) {
+        /** @todo Find a way to DeleteCriticalSection somewhere. */
+        InitializeCriticalSection(&lock);
+        initializedCriticalSection = true;
+    }
+#endif
+
     stackRet = ExtractKeyValueFromRequest(ehRequest, &doWhat, &details);
 
     if(stackRet != OC_STACK_OK)
@@ -1329,29 +1344,21 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
                             OIC_LOG(INFO, TAG, "Building New Call Info.");
                             memset(schedule, 0,
                                     sizeof(ScheduledResourceInfo));
-#ifndef WITH_ARDUINO
-                            pthread_mutex_lock(&lock);
-#endif
+                            MUTEX_LOCK(&lock);
                             schedule->resource = resource;
                             schedule->actionset = actionset;
                             schedule->ehRequest =
                                     (OCServerRequest*) ehRequest->requestHandle;
-#ifndef WITH_ARDUINO
-                            pthread_mutex_unlock(&lock);
-#endif
+                            MUTEX_UNLOCK(&lock);
                             if (delay > 0)
                             {
                                 OIC_LOG_V(INFO, TAG, "delay_time is %ld seconds.",
                                         actionset->timesteps);
-#ifndef WITH_ARDUINO
-                                pthread_mutex_lock(&lock);
-#endif
+                                MUTEX_LOCK(&lock);
                                 schedule->time = registerTimer(delay,
                                         &schedule->timer_id,
                                         &DoScheduledGroupAction);
-#ifndef WITH_ARDUINO
-                                pthread_mutex_unlock(&lock);
-#endif
+                                MUTEX_UNLOCK(&lock);
                                 AddScheduledResource(&scheduleResourceList,
                                         schedule);
                                 stackRet = OC_STACK_OK;
index 869e6ab..5f428b9 100644 (file)
@@ -659,7 +659,7 @@ KeepAliveEntry_t *AddKeepAliveEntry(const CAEndpoint_t *endpoint, OCMode mode,
     entry->timeStamp = OICGetCurrentTime(TIME_IN_US);
     entry->remoteAddr.adapter = endpoint->adapter;
     entry->remoteAddr.flags = endpoint->flags;
-    entry->remoteAddr.interface = endpoint->interface;
+    entry->remoteAddr.ifindex = endpoint->ifindex;
     entry->remoteAddr.port = endpoint->port;
     strncpy(entry->remoteAddr.addr, endpoint->addr, sizeof(entry->remoteAddr.addr));
 
index 0378852..3c817b4 100644 (file)
@@ -604,10 +604,6 @@ OCTagsPayload* OCCopyTagsResources(const char *deviceName, const unsigned char *
     if (id)
     {
         OICStrcpy((char*)tags->di.id, MAX_IDENTITY_SIZE, (char *)id);
-        if (!tags->di.id)
-        {
-            goto memory_allocation_failed;
-        }
     }
     if (baseURI)
     {
index 507f011..2d52917 100644 (file)
@@ -43,11 +43,9 @@ stacktest_env.PrependUnique(CPPPATH = [
                ])
 
 stacktest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
-stacktest_env.AppendUnique(LIBS = ['-lpthread'])
 stacktest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 stacktest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs'])
-stacktest_env.PrependUnique(LIBS = ['m',
-                                    'octbstack',
+stacktest_env.PrependUnique(LIBS = ['octbstack',
                                     'ocsrm',
                                     'connectivity_abstraction',
                                     'coap',
@@ -65,6 +63,12 @@ if env.get('SECURED') == '1':
 if 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', 'pthread'])
+
 ######################################################################
 # Source files and Targets
 ######################################################################
@@ -75,8 +79,9 @@ Alias("test", [stacktests, cbortests])
 
 env.AppendTarget('test')
 if env.get('TEST') == '1':
-       target_os = env.get('TARGET_OS')
-       if target_os == 'linux':
+       if target_os in ['windows']:
+               stacktest_env.AppendENVPath('PATH', [os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk')])
+       if target_os in ['linux', 'windows']:
                 from tools.scons.RunTest import *
                 run_test(stacktest_env,
                          'resource_csdk_stack_test.memcheck',
index 2e4a202..c17afc1 100644 (file)
@@ -33,7 +33,9 @@ extern "C"
 #include <sys/stat.h>
 #include <errno.h>
 #include <fcntl.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 #include <stdlib.h>
 
 //-----------------------------------------------------------------------------
index b780369..7d85b1d 100644 (file)
@@ -21,6 +21,7 @@
 
 extern "C"
 {
+    #include "ocpayload.h"
     #include "ocstack.h"
     #include "ocstackinternal.h"
     #include "logger.h"
@@ -32,7 +33,9 @@ extern "C"
 #include <sys/stat.h>
 #include <errno.h>
 #include <fcntl.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 #include <stdlib.h>
 
 //-----------------------------------------------------------------------------
@@ -85,10 +88,11 @@ extern "C"  OCStackApplicationResult asyncDoResourcesCallback(void* ctx,
     return OC_STACK_KEEP_TRANSACTION;
 }
 
-static void resultCallback(OCDPDev_t *UNUSED1, OCStackResult UNUSED2)
+static void resultCallback(void *UNUSED1, OCDPDev_t *UNUSED2, OCStackResult UNUSED3)
 {
     (void) (UNUSED1);
     (void) (UNUSED2);
+    (void) (UNUSED3);
 }
 
 extern "C" OCStackApplicationResult discoveryCallback(void* ctx,
@@ -224,6 +228,24 @@ TEST(StackStart, StackStartSuccessClientServer)
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
+TEST(StackStart, StackStartSuccessServerThenClient)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+    EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackStart, StackStartSuccessClientThenServer)
+{
+    itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+    EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+    EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER));
+    EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
 TEST(StackStart, StackStartSuccessiveInits)
 {
     itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
@@ -1676,6 +1698,8 @@ TEST(StackResourceAccess, DeleteMiddleResource)
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
+// Visual Studio versions earlier than 2015 have bugs in is_pod and report the wrong answer.
+#if !defined(_MSC_VER) || (_MSC_VER >= 1900)
 TEST(PODTests, OCHeaderOption)
 {
     EXPECT_TRUE(std::is_pod<OCHeaderOption>::value);
@@ -1683,22 +1707,23 @@ TEST(PODTests, OCHeaderOption)
 
 TEST(PODTests, OCCallbackData)
 {
-    EXPECT_TRUE(std::is_pod<OCHeaderOption>::value);
+    EXPECT_TRUE(std::is_pod<OCCallbackData>::value);
 }
+#endif
 
 TEST(OCDoDirectPairingTests, Nullpeer)
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM,OCDoDirectPairing(NULL, pmSel, &pinNumber, &resultCallback));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM,OCDoDirectPairing(NULL, NULL, pmSel, &pinNumber, &resultCallback));
 }
 
 TEST(OCDoDirectPairingTests, NullCallback)
 {
-    EXPECT_EQ(OC_STACK_INVALID_CALLBACK,OCDoDirectPairing(&peer, pmSel, &pinNumber, NULL));
+    EXPECT_EQ(OC_STACK_INVALID_CALLBACK,OCDoDirectPairing(NULL, &peer, pmSel, &pinNumber, NULL));
 }
 
 TEST(OCDoDirectPairingTests, NullpinNumber)
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM,OCDoDirectPairing(&peer, pmSel, NULL, &resultCallback));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM,OCDoDirectPairing(NULL, &peer, pmSel, NULL, &resultCallback));
 }
 
 TEST(StackResource, MultipleResourcesDiscovery)
@@ -1753,3 +1778,29 @@ TEST(StackResource, MultipleResourcesDiscovery)
 
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
+
+TEST(StackPayload, CloneByteString)
+{
+    uint8_t bytes[] = { 0, 1, 2, 3 };
+    OCByteString byteString;
+    byteString.bytes = bytes;
+    byteString.len = sizeof(bytes);
+
+    OCRepPayload *original = OCRepPayloadCreate();
+    ASSERT_TRUE(original != NULL);
+    EXPECT_TRUE(OCRepPayloadSetPropByteString(original, "name", byteString));
+
+    OCRepPayload *clone = OCRepPayloadClone(original);
+    ASSERT_TRUE(clone != NULL);
+
+    OCRepPayloadDestroy(original);
+
+    OCByteString cloneByteString;
+    EXPECT_TRUE(OCRepPayloadGetPropByteString(clone, "name", &cloneByteString));
+    ASSERT_TRUE(cloneByteString.bytes != NULL);
+    EXPECT_EQ(sizeof(bytes), cloneByteString.len);
+    EXPECT_TRUE(0 == memcmp(bytes, cloneByteString.bytes, sizeof(bytes)));
+    OICFree(cloneByteString.bytes);
+
+    OCRepPayloadDestroy(clone);
+}
index 5d84295..74cd6dd 100644 (file)
@@ -40,7 +40,7 @@ examples_env.AppendUnique(CPPPATH = [
                ])
 
 target_os = env.get('TARGET_OS')
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
        examples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
 
        # Note: 'pthread' is in libc for android. On other platform, if use
@@ -56,8 +56,14 @@ examples_env.AppendUnique(LIBS = ['oc_logger'])
 examples_env.AppendUnique(LIBS = ['octbstack'])
 examples_env.AppendUnique(LIBS = ['oc'])
 
+if target_os in ['msys_nt', 'windows']:
+       examples_env.PrependUnique(LIBS = ['mswsock', 'ws2_32', 'iphlpapi', 'ole32'])
+
 if env.get('SECURED') == '1':
-    examples_env.AppendUnique(LIBS = ['tinydtls'])
+       examples_env.AppendUnique(LIBS = ['tinydtls'])
+       examples_env.AppendUnique(CPPDEFINES = ['_WITH_DTLS_'])
+       if target_os in ['msys_nt', 'windows']:
+               examples_env.AppendUnique(LIBS = ['advapi32'])
 
 if target_os == 'android':
        examples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
@@ -69,43 +75,60 @@ if target_os == 'android':
 if target_os in ['darwin', 'ios']:
        examples_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
 
+if env.get('LOGGING'):
+       examples_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+if target_os in ['msys_nt', 'windows']:
+       examples_env.AppendUnique(LIBS = ['Comctl32', 'Gdi32', 'User32'])
+
+if env.get('LOGGING'):
+       examples_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+def make_single_file_cpp_program(program_name):
+       return examples_env.Program(program_name, program_name + ".cpp")
+
 ######################################################################
 # Source files and Targets
 ######################################################################
-simpleserver = examples_env.Program('simpleserver', 'simpleserver.cpp')
-simpleclient = examples_env.Program('simpleclient', 'simpleclient.cpp')
-simpleserverHQ = examples_env.Program('simpleserverHQ', 'simpleserverHQ.cpp')
-simpleclientHQ = examples_env.Program('simpleclientHQ', 'simpleclientHQ.cpp')
-fridgeserver = examples_env.Program('fridgeserver', 'fridgeserver.cpp')
-fridgeclient = examples_env.Program('fridgeclient', 'fridgeclient.cpp')
-presenceserver = examples_env.Program('presenceserver', 'presenceserver.cpp')
-presenceclient = examples_env.Program('presenceclient', 'presenceclient.cpp')
-simpleclientserver = examples_env.Program('simpleclientserver', 'simpleclientserver.cpp')
-roomserver = examples_env.Program('roomserver', 'roomserver.cpp')
-roomclient = examples_env.Program('roomclient', 'roomclient.cpp')
-garageserver = examples_env.Program('garageserver', 'garageserver.cpp')
-garageclient = examples_env.Program('garageclient', 'garageclient.cpp')
-groupserver = examples_env.Program('groupserver', 'groupserver.cpp')
-groupclient = examples_env.Program('groupclient', 'groupclient.cpp')
-lightserver = examples_env.Program('lightserver', 'lightserver.cpp')
-devicediscoveryserver = examples_env.Program('devicediscoveryserver', 'devicediscoveryserver.cpp')
-devicediscoveryclient = examples_env.Program('devicediscoveryclient', 'devicediscoveryclient.cpp')
-threadingsample = examples_env.Program('threadingsample', 'threadingsample.cpp')
+example_names = [
+       'simpleserver', 'simpleclient',
+       'simpleclientserver',
+       'directpairingclient',
+       'devicediscoveryserver', 'devicediscoveryclient'
+       ]
+
+if target_os not in ['windows', 'msys_nt']:
+       example_names += [
+               'simpleserverHQ', 'simpleclientHQ',
+               'fridgeserver', 'fridgeclient',
+               'presenceserver', 'presenceclient',
+               'roomserver', 'roomclient',
+               'garageserver',
+               'garageclient',
+               'groupserver',
+               'groupclient',
+               'lightserver',
+               'threadingsample',
+               ]
 
+examples = map(make_single_file_cpp_program, example_names)
+
+######################################################################
+# Other examples
+######################################################################
 clientjson = examples_env.Install(env.get('BUILD_DIR') + '/resource/examples/',
                                env.get('SRC_DIR') + '/resource/examples/' + 'oic_svr_db_client.dat')
 serverjson = examples_env.Install(env.get('BUILD_DIR') + '/resource/examples/',
                                env.get('SRC_DIR') + '/resource/examples/' + 'oic_svr_db_server.dat')
-Alias("examples", [simpleserver, simpleclient,
-               simpleserverHQ, simpleclientHQ,
-               fridgeserver, fridgeclient,
-               presenceserver, presenceclient,
-               simpleclientserver, roomserver, roomclient, garageserver,
-               garageclient,
-               groupserver, groupclient,
-               lightserver,
-               devicediscoveryserver, devicediscoveryclient,
-               threadingsample,
-               serverjson, clientjson
-     ])
+directpairingdat = examples_env.Install(env.get('BUILD_DIR') + '/resource/examples/',
+                               env.get('SRC_DIR') + '/resource/examples/' + 'oic_svr_db_client_directpairing.dat')
+
+examples += [clientjson, serverjson, directpairingdat]
+
+if target_os in ['msys_nt', 'windows']:
+       winUIClient = examples_env.Program('winUIClient', ['winuiclientgui.cpp', 'winuiclient.cpp'])
+       mediaserver = examples_env.Program('mediaserver', 'mediaserver.cpp')
+       examples += [winUIClient, mediaserver]
+
+Alias("examples", examples)
 env.AppendTarget('examples')
index 2112ae6..dba1515 100644 (file)
@@ -33,7 +33,7 @@
 
 using namespace OC;
 
-//Set of strings for each of deviceInfo fields
+//Set of strings for each of platform Info fields
 std::string dateOfManufacture = "myDateOfManufacture";
 std::string firmwareVersion = "my.Firmware.Version";
 std::string manufacturerName = "myName";
@@ -46,8 +46,10 @@ std::string platformVersion = "platformVersion";
 std::string supportUrl = "www.mysupporturl.com";
 std::string systemTime = "mySystemTime";
 
-//Set of strings for each of platform info fields
+//Set of strings for each of device info fields
 std::string deviceName = "Bill's Battlestar";
+std::string specVersion = "myDeviceSpecVersion";
+std::string dataModelVersions = "myDeviceModelVersion";
 
 //OCPlatformInfo Contains all the platform info to be stored
 OCPlatformInfo platformInfo;
@@ -74,6 +76,8 @@ void DeletePlatformInfo()
 void DeleteDeviceInfo()
 {
     delete[] deviceInfo.deviceName;
+    delete[] deviceInfo.specVersion;
+    OCFreeOCStringLL(deviceInfo.dataModelVersions);
 }
 
 void DuplicateString(char ** targetString, std::string sourceString)
@@ -102,9 +106,16 @@ OCStackResult SetPlatformInfo(std::string platformID, std::string manufacturerNa
 }
 
 
-OCStackResult SetDeviceInfo(std::string deviceName)
+OCStackResult SetDeviceInfo(std::string deviceName, std::string specVersion, std::string dataModelVersions)
 {
     DuplicateString(&deviceInfo.deviceName, deviceName);
+
+    if (!specVersion.empty())
+        DuplicateString(&deviceInfo.specVersion, specVersion);
+
+    if (!dataModelVersions.empty())
+        OCResourcePayloadAddStringLL(&deviceInfo.dataModelVersions, dataModelVersions.c_str());
+
     return OC_STACK_OK;
 }
 
@@ -137,7 +148,7 @@ int main()
     }
 
 
-    result = SetDeviceInfo(deviceName);
+    result = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
     OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.wk.d");
     OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.d.tv");
 
diff --git a/resource/examples/directpairingclient.cpp b/resource/examples/directpairingclient.cpp
new file mode 100644 (file)
index 0000000..dfea47c
--- /dev/null
@@ -0,0 +1,412 @@
+/* *****************************************************************
+ *
+ * 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 <string.h>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <string>
+#include <map>
+#include <cstdlib>
+#include <mutex>
+#include <condition_variable>
+
+#include "logger.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+#define MAX_URI_LENGTH (64)
+#define MAX_PERMISSION_LENGTH (5)
+#define CREATE (1)
+#define READ (2)
+#define UPDATE (4)
+#define DELETE (8)
+#define NOTIFY (16)
+#define DASH '-'
+#define PREDEFINED_TIMEOUT (10)
+#define MAX_OWNED_DEVICE (10)
+#define TAG  "provisioningclient"
+
+#define JSON_DB_PATH "./oic_svr_db_client.json"
+#define DAT_DB_PATH "./oic_svr_db_client.dat"
+#define DEV_STATUS_ON "DEV_STATUS_ON"
+#define DEV_STATUS_OFF "DEV_STATUS_OFF"
+
+#define DP_DISCOVERY_TIMEOUT 4
+#define DP_PIN_LENGTH 8
+
+#define BOLD_BEGIN    "\033[1m"
+#define RED_BEGIN     "\033[1;31m"
+#define GREEN_BEGIN   "\033[1;92m"
+#define COLOR_END     "\033[0m"
+
+using namespace OC;
+
+static int ask = 1;
+static PairedDevices discoveredDeviceList, pairedDeviceList;
+
+static FILE* client_open(const char* /*fileName*/, const char *mode)
+{
+    return fopen(DAT_DB_PATH, mode);
+}
+
+
+static void printMenu()
+{
+    std::cout << GREEN_BEGIN "Choose an option:" COLOR_END<<std::endl;
+    std::cout << GREEN_BEGIN "# 1 (DP device discovery) : discover Direct-Pairing devices"
+        COLOR_END<<std::endl;
+    std::cout << GREEN_BEGIN "# 2 (start Direct-Pairing) : negotiate DP method & start Direct-Pairin"
+        COLOR_END<<std::endl;
+    std::cout << GREEN_BEGIN "# 3 (list all device) : list all discovered/paired devices"
+        COLOR_END<<std::endl;
+    std::cout << GREEN_BEGIN "# 4 (send data) : send data to device" COLOR_END<<std::endl;
+    std::cout << GREEN_BEGIN "# 9 (quit) : quit test " COLOR_END<<std::endl;
+}
+
+static void printPrompt()
+{
+    std::cout << BOLD_BEGIN "IoTivity-DP#" COLOR_END" ";
+}
+
+static void printDevices(PairedDevices& list)
+{
+    for (size_t i = 0; i < list.size(); i++)
+    {
+        std::cout << "["<< i+1 << "]" << " ID: " << list[i]->getDeviceID() << std::endl;
+    }
+}
+
+static void findCallback(PairedDevices discoveredDevList)
+{
+
+    if (0 == discoveredDevList.size())
+    {
+        std::cout<< "No Direct-pairing Support device Found" << std::endl;
+    }
+    else
+    {
+        std::cout << "Discovered Direct-Pairing Support Device"<< std::endl;
+        discoveredDeviceList = discoveredDevList;
+        printDevices(discoveredDevList);
+    }
+
+    printMenu();
+    printPrompt();
+    fflush(NULL);
+}
+
+static bool printPairingMethod(int choice)
+{
+    if (NULL == discoveredDeviceList[choice])// || false == discoveredDeviceList[choice]->edp)
+    {
+        std::cout<< "Invalid device or Not support direct-pairing..\n\n" << std::endl;
+        return false;
+    }
+
+    auto prms = discoveredDeviceList[choice]->getPairingMethods();
+    if (0 == prms.size())
+    {
+        std::cout << "Not exist any support method..\n\n" << std::endl;
+        return false;
+    }
+
+    bool ret = true;
+    std::cout << "\n* List of supported pairing methods *" << std::endl;
+
+    for (unsigned int i = 0; i < prms.size(); i++)
+    {
+        std::cout<< "[" << i+1 << "]";
+        switch (prms[i])
+        {
+            case DP_PRE_CONFIGURED:
+                std::cout<<"Pre-Configured PIN"<<std::endl;;
+                break;
+            case DP_RANDOM_PIN:
+                std::cout<<"Random PIN"<<std::endl;;
+                break;
+            default:
+                std::cout<<"NOT Allowed ("<< prms[i]<<")"<<std::endl;
+                ret = false;
+                break;
+        }
+        std::cout<<std::endl;
+    }
+
+    return ret;
+}
+
+static void resultCallback(std::shared_ptr<OCDirectPairing> ptr, OCStackResult result)
+{
+
+    if (OC_STACK_OK == result)
+    {
+        std::cout << " Direct-Pairing SUCCESS" << std::endl;
+        std::cout << "Taget Add info:" << ptr->getHost() << std::endl;
+    }
+    else {
+        std::cout <<" Direct-Pairing FAILED" << std::endl;
+    }
+
+    printMenu();
+    printPrompt();
+    fflush(NULL);
+}
+
+static void pairedDevListCB(PairedDevices pairedDevList)
+{
+
+    if (0 == pairedDevList.size())
+    {
+        std::cout << "No Paired Devcie  Found" << std::endl;
+    }
+    else
+    {
+        pairedDeviceList = pairedDevList;
+        printDevices(pairedDevList);
+    }
+
+    printMenu();
+    printPrompt();
+    fflush(NULL);
+}
+
+static void getCallback(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+{
+    (void)(headerOptions);
+    try
+    {
+        if (OC_STACK_OK == eCode)
+        {
+            std::cout << "Callback Context for GET query recvd successfully" << std::endl;
+            std::cout << "Resource URI: " << rep.getUri() << std::endl;
+
+            bool state = false;
+            int power = 0;
+            rep.getValue("state", state);
+            rep.getValue("power", power);
+
+            std::cout << "\tstate: " << state << std::endl;
+            std::cout << "\tpower: " << power << std::endl;
+        }
+        else
+        {
+            std::cout << "getCallback Response error: " << eCode << std::endl;
+        }
+    }
+    catch(std::exception& e)
+    {
+        std::cout << "Exception: " << e.what() << " in onGet" << std::endl;
+    }
+}
+
+static bool InputPIN(std::string& pin)
+{
+    std::cout <<"   > Enter PIN Number for authentication (ex - '00000000' [8 digit] ):" ;
+
+    std::cin >> pin;
+
+    if (pin.size() != DP_PIN_LENGTH)
+    {
+        std::cout<<"Invalid PIN"<<std::endl;
+        return false;
+    }
+
+    return true;
+}
+
+int main(void)
+{
+    OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
+
+    // Create PlatformConfig object
+    PlatformConfig cfg {
+        OC::ServiceType::InProc,
+            OC::ModeType::Both,
+            "0.0.0.0",
+            0,
+            OC::QualityOfService::LowQos,
+            &ps
+    };
+
+    OCPlatform::Configure(cfg);
+
+    try
+    {
+        unsigned int choice;
+        for (int out = 0; !out;)
+        {
+            if (ask)
+            {
+                printMenu();
+                printPrompt();
+                fflush(NULL);
+            }
+            std::cin >> choice;
+
+            switch(choice) {
+                case 1:
+                    {
+                        OCStackResult result = OC::OCPlatform::findDirectPairingDevices(
+                                DP_DISCOVERY_TIMEOUT, findCallback);
+
+                        if (OC_STACK_NO_RESOURCE == result)
+                        {
+                            std::cout << "!! No Direct-Pairing Support Device found"<<std::endl;
+                            break;
+                        }
+
+                        if (OC_STACK_OK != result)
+                        {
+                            std::cout << "!!Error - findDirectPairingDevices failed."<<std::endl;
+                        }
+                        ask = 0;
+                        break;
+                    }
+                case 2:
+                    {
+                        unsigned int pMethodIDx = -1;
+                        std::string pin("");
+
+                        std::cout << "- Negotiate DP method & Start Direct-Pairing - ";
+                        std::cout << "* List of  discovered device" << std::endl;
+                        printDevices(discoveredDeviceList);
+                        std::cout << "   > Enter Peer Device Number to initiate Direct-Pairing:" << std::endl;
+                        printPrompt();
+                        std::cin >> choice;
+                        if (choice < 1 || choice > discoveredDeviceList.size())
+                        {
+                            std::cout << "!!Device Number is incorrect, Try Again" << std::endl;
+                            break;
+                        }
+                        OCPrm_t pmSel = DP_NOT_ALLOWED;
+                        choice--;
+                        if (false == printPairingMethod(choice))
+                        {
+                            std::cout << "Target does not support the Direct-Pairing" << std::endl;
+                            break;
+                        }
+
+                        std::cout << " > Enter pairing method: "<< std::endl;
+                        printPrompt();
+                        std::cin >> pMethodIDx;
+                        auto prms = discoveredDeviceList[choice]->getPairingMethods();
+                        if (0 >= pMethodIDx || prms.size() < pMethodIDx)
+                        {
+                            std::cout <<"Invalid mode selection" << std::endl;
+                            break;
+                        }
+
+                        pmSel =  prms[pMethodIDx - 1];
+                        if (false == InputPIN(pin))
+                        {
+                            break;
+                        }
+
+                        OCStackResult result = OC::OCPlatform::doDirectPairing(discoveredDeviceList[choice], pmSel, pin, resultCallback);
+
+                        if (OC_STACK_OK != result)
+                        {
+                            std::cout << "!!Error - doDirectPairing failed." << std::endl;
+                        }
+                        ask = 0;
+                        break;
+                    }
+                case 3:
+                    {
+                        std::cout << "- List all discovered and paired devices) -";
+                        std::cout << "  > List of discovered devices" << std::endl;
+                        printDevices(discoveredDeviceList);
+                        std::cout << std::endl;
+
+                        std::cout << "  > List of paired devices" << std::endl;
+                        OCStackResult result = OC::OCPlatform::getDirectPairedDevices(pairedDevListCB);
+                        printDevices(pairedDeviceList);
+                        std::cout << std::endl;
+
+                        if (OC_STACK_NO_RESOURCE == result)
+                        {
+                            std::cout << "!! No Paired device found"<<std::endl;
+                            break;
+                        }
+                        if (OC_STACK_OK != result)
+                        {
+                            std::cout << "!!Error - getDirectPairedDevices failed."<<std::endl;
+                        }
+                        break;
+                    }
+                case 4:
+                    {
+                        std::cout << "- Send data(GET Request) to device(led server) -" << std::endl;
+                        printDevices(pairedDeviceList);
+                        pairedDeviceList = discoveredDeviceList;
+                        printMenu();
+                        std::cout << "Enter device number to GET data: ";
+                        std::cin >> choice;
+                        choice--;
+
+                        std::vector<std::string> ledTypes = {"core.led"};
+                        std::vector<std::string> ifaces = {DEFAULT_INTERFACE};
+
+                        OCConnectivityType ct = pairedDeviceList[choice]->getConnType();
+
+                        std::cout << "\n\n HOST address is : " << pairedDeviceList[choice]->getHost() << "\n\n";
+                        OCResource::Ptr led = OC::OCPlatform::constructResourceObject(
+                                pairedDeviceList[choice]->getHost(),
+                                "/a/led", ct, false, ledTypes, ifaces);
+
+                        if(!led)
+                        {
+                            std::cout << "Error: Led Object construction returned null" << std::endl;
+                            break;
+                        }
+                        OCStackResult res = led->get(QueryParamsMap(), getCallback);
+
+                        if (OC_STACK_OK != res)
+                        {
+                            std::cout << "Error: get Failed for Led" << std::endl;
+                        }
+                        break;
+                    }
+                case 9:
+                    {
+                        out = 1;
+                        break;
+                    }
+                default:
+                    {
+                        std::cout << GREEN_BEGIN "Wrong Option : Try Again" COLOR_END << std::endl;
+                        printMenu();
+                        printPrompt();
+                        break;
+                    }
+            }
+        }
+    }
+    catch(OCException& e)
+    {
+        oclog() << "Exception in main: "<< e.what();
+    }
+
+    return 0;
+}
index dbc91ea..556b34c 100644 (file)
@@ -114,6 +114,9 @@ class DeviceResource : public Resource
             std::string clientAPIVersion;
             std::string clientToken;
 
+            // Get the message ID from the request
+            std::cout << " MessageID: " << request->getMessageID() << std::endl;
+
             // Search the header options map and look for API version and Client token
             for (auto it = headerOptions.begin(); it != headerOptions.end(); ++it)
             {
index dd207d5..6368e93 100644 (file)
@@ -24,6 +24,9 @@
 /// (properties and methods) and host this resource on the server.
 ///
 
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
 #include <functional>
 
 #include <pthread.h>
diff --git a/resource/examples/mediaserver.cpp b/resource/examples/mediaserver.cpp
new file mode 100644 (file)
index 0000000..4fc5fa5
--- /dev/null
@@ -0,0 +1,637 @@
+/* ****************************************************************
+ *
+ * Copyright 2016 Intel Corporation All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+///
+/// This sample provides steps to define an interface for a resource
+/// (properties and methods) and host this resource on the server.
+///
+
+#include <functional>
+#include <mutex>
+#include "platform_features.h"
+#include <condition_variable>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include <windows.h>
+#include <objbase.h>
+
+#include <commctrl.h>
+#include <mmdeviceapi.h>
+#include <endpointvolume.h>
+#include <stdio.h>
+#include <math.h>       /* log */
+
+#define SAFE_RELEASE(x)  \
+              if ((x) != NULL)  \
+                { (x)->Release(); (x) = NULL; }
+
+using namespace OC;
+using namespace std;
+namespace PH = std::placeholders;
+
+int gObservation = 0;
+void * ChangeMediaRepresentation (void *param);
+void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest);
+void playPause(void);
+void setVolume(int vol);
+int getVolume(void);
+
+// Specifies where to notify all observers or list of observers
+// false: notifies all observers
+// true: notifies list of observers
+bool isListOfObservers = false;
+
+// Specifies secure or non-secure
+// false: non-secure resource
+// true: secure resource
+bool isSecure = false;
+
+/// Specifies whether Entity handler is going to do slow response or not
+bool isSlowResponse = false;
+
+
+// Forward declaring the entityHandler
+
+/// This class represents a single resource named 'MediaResource'. This resource has
+/// two simple properties named 'state' and 'volume'
+
+class MediaResource
+{
+
+public:
+    /// Access this property from a TB client
+    std::string m_name;
+    bool m_state;
+    int m_volume;
+    std::string m_mediaUri;
+    OCResourceHandle m_resourceHandle;
+    OCRepresentation m_mediaRep;
+    ObservationIds m_interestedObservers;
+
+public:
+    /// Constructor
+    MediaResource()
+        :m_name("Media Player"), m_state(false), m_volume(0), m_mediaUri("/a/media"),
+                m_resourceHandle(nullptr)
+    {
+        // Initialize representation
+        m_mediaRep.setUri(m_mediaUri);
+
+        m_mediaRep.setValue("state", m_state);
+        m_mediaRep.setValue("volume", m_volume);
+        m_mediaRep.setValue("name", m_name);
+    }
+
+    /* Note that this does not need to be a member function: for classes you do not have
+    access to, you can accomplish this with a free function: */
+
+    /// This function internally calls registerResource API.
+    void createResource()
+    {
+        //URI of the resource
+        std::string resourceURI = m_mediaUri;
+        //resource type name. In this case, it is media
+        std::string resourceTypeName = "core.media";
+        // resource interface.
+        std::string resourceInterface = DEFAULT_INTERFACE;
+
+        // OCResourceProperty is defined ocstack.h
+        uint8_t resourceProperty;
+        if(isSecure)
+        {
+            resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE;
+        }
+        else
+        {
+            resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
+        }
+        EntityHandler cb = std::bind(&MediaResource::entityHandler, this,PH::_1);
+
+        // This will internally create and register the resource.
+        OCStackResult result = OCPlatform::registerResource(
+                                    m_resourceHandle, resourceURI, resourceTypeName,
+                                    resourceInterface, cb, resourceProperty);
+
+        if (OC_STACK_OK != result)
+        {
+            cout << "Resource creation was unsuccessful\n";
+        }
+    }
+
+    OCResourceHandle getHandle()
+    {
+        return m_resourceHandle;
+    }
+
+    // Puts representation.
+    // Gets values from the representation and
+    // updates the internal state
+    void put(OCRepresentation& rep)
+    {
+        try
+        {
+            if (rep.getValue("state", m_state))
+            {
+                cout << "\t\t\t\t" << "state: " << m_state << endl;
+                if(m_state)
+                {
+                    playPause();
+                }
+            }
+            else
+            {
+                cout << "\t\t\t\t" << "state not found in the representation" << endl;
+            }
+
+            if (rep.getValue("volume", m_volume))
+            {
+                cout << "\t\t\t\t" << "volume: " << m_volume << endl;
+                if((0 <= m_volume) && (m_volume <= 100))
+                {
+                    setVolume(m_volume);
+                }
+            }
+            else
+            {
+                cout << "\t\t\t\t" << "volume not found in the representation" << endl;
+            }
+        }
+        catch (exception& e)
+        {
+            cout << e.what() << endl;
+        }
+
+    }
+
+    // Post representation.
+    // Post can create new resource or simply act like put.
+    // Gets values from the representation and
+    // updates the internal state
+    OCRepresentation post(OCRepresentation& rep)
+    {
+        put(rep);
+        return get();
+    }
+
+
+    // gets the updated representation.
+    // Updates the representation with latest internal state before
+    // sending out.
+    OCRepresentation get()
+    {
+        m_mediaRep.setValue("state", m_state);
+        m_mediaRep.setValue("volume", m_volume);
+
+        return m_mediaRep;
+    }
+
+    void addType(const std::string& type) const
+    {
+        OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
+        if (OC_STACK_OK != result)
+        {
+            cout << "Binding TypeName to Resource was unsuccessful\n";
+        }
+    }
+
+    void addInterface(const std::string& intf) const
+    {
+        OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, intf);
+        if (OC_STACK_OK != result)
+        {
+            cout << "Binding TypeName to Resource was unsuccessful\n";
+        }
+    }
+
+private:
+// This is just a sample implementation of entity handler.
+// Entity handler can be implemented in several ways by the manufacturer
+OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
+{
+    cout << "\tIn Server CPP entity handler:\n";
+    OCEntityHandlerResult ehResult = OC_EH_ERROR;
+    if(request)
+    {
+        // Get the request type and request flag
+        std::string requestType = request->getRequestType();
+        int requestFlag = request->getRequestHandlerFlag();
+
+        if(requestFlag & RequestHandlerFlag::RequestFlag)
+        {
+            cout << "\t\trequestFlag : Request\n";
+            auto pResponse = std::make_shared<OC::OCResourceResponse>();
+            pResponse->setRequestHandle(request->getRequestHandle());
+            pResponse->setResourceHandle(request->getResourceHandle());
+
+            // Check for query params (if any)
+            QueryParamsMap queries = request->getQueryParameters();
+
+            if (!queries.empty())
+            {
+                cout << "\nQuery processing upto entityHandler" << std::endl;
+            }
+            for (auto it : queries)
+            {
+                cout << "Query key: " << it.first << " value : " << it.second
+                        << std::endl;
+            }
+
+            // If the request type is GET
+            if(requestType == "GET")
+            {
+                cout << "\t\t\trequestType : GET\n";
+                if(isSlowResponse) // Slow response case
+                {
+                    static int startedThread = 0;
+                    if(!startedThread)
+                    {
+                        std::thread t(handleSlowResponse, (void *)this, request);
+                        startedThread = 1;
+                        t.detach();
+                    }
+                    ehResult = OC_EH_SLOW;
+                }
+                else // normal response case.
+                {
+                    pResponse->setErrorCode(200);
+                    pResponse->setResponseResult(OC_EH_OK);
+                    pResponse->setResourceRepresentation(get());
+                    if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                    {
+                        ehResult = OC_EH_OK;
+                    }
+                }
+            }
+            else if(requestType == "PUT")
+            {
+                cout << "\t\t\trequestType : PUT\n";
+                OCRepresentation rep = request->getResourceRepresentation();
+
+                // Do related operations related to PUT request
+                // Update the mediaResource
+                put(rep);
+                pResponse->setErrorCode(200);
+                pResponse->setResponseResult(OC_EH_OK);
+                pResponse->setResourceRepresentation(get());
+                if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                {
+                    ehResult = OC_EH_OK;
+                }
+            }
+            else if(requestType == "POST")
+            {
+                cout << "\t\t\trequestType : POST\n";
+
+                OCRepresentation rep = request->getResourceRepresentation();
+
+                // Do related operations related to POST request
+                OCRepresentation rep_post = post(rep);
+                pResponse->setResourceRepresentation(rep_post);
+                pResponse->setErrorCode(200);
+                if(rep_post.hasAttribute("createduri"))
+                {
+                    pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
+                    pResponse->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
+                }
+                else
+                {
+                    pResponse->setResponseResult(OC_EH_OK);
+                }
+
+                if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                {
+                    ehResult = OC_EH_OK;
+                }
+            }
+            else if(requestType == "DELETE")
+            {
+                cout << "Delete request received" << endl;
+            }
+        }
+
+        if(requestFlag & RequestHandlerFlag::ObserverFlag)
+        {
+            ObservationInfo observationInfo = request->getObservationInfo();
+            if(ObserveAction::ObserveRegister == observationInfo.action)
+            {
+                m_interestedObservers.push_back(observationInfo.obsId);
+            }
+            else if(ObserveAction::ObserveUnregister == observationInfo.action)
+            {
+                m_interestedObservers.erase(std::remove(
+                                                            m_interestedObservers.begin(),
+                                                            m_interestedObservers.end(),
+                                                            observationInfo.obsId),
+                                                            m_interestedObservers.end());
+            }
+
+            cout << "\t\trequestFlag : Observer\n";
+            gObservation = 1;
+            static int startedThread = 0;
+
+            // Observation happens on a different thread in ChangeMediaRepresentation function.
+            // If we have not created the thread already, we will create one here.
+
+            if(!startedThread)
+            {
+                std::thread t(ChangeMediaRepresentation, (void *)this);
+                startedThread = 1;
+                t.detach();
+            }
+
+            ehResult = OC_EH_OK;
+        }
+    }
+    else
+    {
+        cout << "Request invalid" << std::endl;
+    }
+
+    return ehResult;
+}
+
+};
+
+// ChangeMediaRepresentaion is an observation function,
+// which notifies any changes to the resource to stack
+// via notifyObservers
+void * ChangeMediaRepresentation (void *param)
+{
+    int prevVolume = 0;
+    MediaResource* mediaPtr = (MediaResource*) param;
+
+    // This function continuously monitors for the changes
+    while (1)
+    {
+        Sleep(100);
+
+        if (gObservation)
+        {
+            prevVolume = mediaPtr->m_volume;
+            mediaPtr->m_volume = getVolume();
+            if (prevVolume == mediaPtr->m_volume)
+                continue;
+
+            cout << "Volume changed from " << prevVolume << "% to " << mediaPtr->m_volume << "%\n";
+
+            // If under observation if there are any changes to the media resource
+            // we call notifyObservors
+            //
+            // For demostration we are changing the volume value and notifying.
+
+            cout << "\nVolume updated to : " << mediaPtr->m_volume << endl;
+            cout << "Notifying observers with resource handle: " << mediaPtr->getHandle() << endl;
+
+            OCStackResult result = OC_STACK_OK;
+
+            if(isListOfObservers)
+            {
+                std::shared_ptr<OCResourceResponse> resourceResponse =
+                            {std::make_shared<OCResourceResponse>()};
+
+                resourceResponse->setErrorCode(200);
+                resourceResponse->setResourceRepresentation(mediaPtr->get(), DEFAULT_INTERFACE);
+
+                result = OCPlatform::notifyListOfObservers(  mediaPtr->getHandle(),
+                                                             mediaPtr->m_interestedObservers,
+                                                             resourceResponse);
+            }
+            else
+            {
+                result = OCPlatform::notifyAllObservers(mediaPtr->getHandle());
+            }
+
+            if(OC_STACK_NO_OBSERVERS == result)
+            {
+                cout << "No More observers, stopping notifications" << endl;
+                gObservation = 0;
+            }
+        }
+    }
+
+    return NULL;
+}
+
+void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest)
+{
+    // This function handles slow response case
+    MediaResource* mediaPtr = (MediaResource*) param;
+    // Induce a case for slow response by using sleep
+    cout << "SLOW response" << std::endl;
+    sleep (10);
+
+    auto pResponse = std::make_shared<OC::OCResourceResponse>();
+    pResponse->setRequestHandle(pRequest->getRequestHandle());
+    pResponse->setResourceHandle(pRequest->getResourceHandle());
+    pResponse->setResourceRepresentation(mediaPtr->get());
+    pResponse->setErrorCode(200);
+    pResponse->setResponseResult(OC_EH_OK);
+
+    // Set the slow response flag back to false
+    isSlowResponse = false;
+    OCPlatform::sendResponse(pResponse);
+    return NULL;
+}
+
+void PrintUsage()
+{
+    cout << std::endl;
+    cout << "Usage : mediaserver <value>\n";
+    cout << "    Default - Non-secure resource and notify all observers\n";
+    cout << "    1 - Non-secure resource and notify list of observers\n\n";
+    cout << "    2 - Secure resource and notify all observers\n";
+    cout << "    3 - Secure resource and notify list of observers\n\n";
+    cout << "    4 - Non-secure resource, GET slow response, notify all observers\n";
+}
+
+static FILE* client_open(const char* /*path*/, const char *mode)
+{
+    return fopen("./oic_svr_db_server.json", mode);
+}
+
+void playPause()
+{
+    INPUT ip;
+
+    // Set up a generic keyboard event.
+    ip.type = INPUT_KEYBOARD;
+    ip.ki.wScan = 0; // hardware scan code for key
+    ip.ki.time = 0;
+    ip.ki.dwExtraInfo = 0;
+    ip.ki.wVk = VK_MEDIA_PLAY_PAUSE; // virtual-key code for the "a" key
+    ip.ki.dwFlags = 0; // 0 for key press
+
+    SendInput(1, &ip, sizeof(INPUT));
+    // Release the "Play/Pause" key
+    ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release
+    SendInput(1, &ip, sizeof(INPUT));
+}
+
+int getVolume()
+{
+    IAudioEndpointVolume *g_pEndptVol = NULL;
+    HRESULT hr = S_OK;
+    IMMDeviceEnumerator *pEnumerator = NULL;
+    IMMDevice *pDevice = NULL;
+    OSVERSIONINFO VersionInfo;
+
+    ZeroMemory(&VersionInfo, sizeof(OSVERSIONINFO));
+    VersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+    GetVersionEx(&VersionInfo);
+    CoInitialize(NULL);
+
+    // Get enumerator for audio endpoint devices.
+    hr = CoCreateInstance(__uuidof(MMDeviceEnumerator),
+                          NULL, CLSCTX_INPROC_SERVER,
+                          __uuidof(IMMDeviceEnumerator),
+                          (void**)&pEnumerator);
+
+    // Get default audio-rendering device.
+    hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &pDevice);
+
+    hr = pDevice->Activate(__uuidof(IAudioEndpointVolume),
+                           CLSCTX_ALL, NULL, (void**)&g_pEndptVol);
+    float currentVal;
+    hr = g_pEndptVol->GetMasterVolumeLevelScalar(&currentVal);
+    fflush(stdout); // just in case
+
+    SAFE_RELEASE(pEnumerator)
+    SAFE_RELEASE(pDevice)
+    SAFE_RELEASE(g_pEndptVol)
+    CoUninitialize();
+    return ((int) round(100 * currentVal));
+
+}
+
+void setVolume(int vol)
+{
+    IAudioEndpointVolume *g_pEndptVol = NULL;
+    HRESULT hr = S_OK;
+    IMMDeviceEnumerator *pEnumerator = NULL;
+    IMMDevice *pDevice = NULL;
+    OSVERSIONINFO VersionInfo;
+
+    ZeroMemory(&VersionInfo, sizeof(OSVERSIONINFO));
+    VersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+    GetVersionEx(&VersionInfo);
+    CoInitialize(NULL);
+
+    // Get enumerator for audio endpoint devices.
+    hr = CoCreateInstance(__uuidof(MMDeviceEnumerator),
+                          NULL, CLSCTX_INPROC_SERVER,
+                          __uuidof(IMMDeviceEnumerator),
+                          (void**)&pEnumerator);
+
+    // Get default audio-rendering device.
+    hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &pDevice);
+
+    hr = pDevice->Activate(__uuidof(IAudioEndpointVolume),
+                           CLSCTX_ALL, NULL, (void**)&g_pEndptVol);
+    float got = (float)vol/100.0; // needs to be within 1.0 to 0.0
+    hr = g_pEndptVol->SetMasterVolumeLevelScalar(got, NULL);
+    fflush(stdout); // just in case
+
+    SAFE_RELEASE(pEnumerator)
+    SAFE_RELEASE(pDevice)
+    SAFE_RELEASE(g_pEndptVol)
+    CoUninitialize();
+}
+
+int main(int argc, char* argv[])
+{
+    OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
+
+    if (argc == 1)
+    {
+        isListOfObservers = false;
+        isSecure = false;
+    }
+    else if (argc == 2)
+    {
+        int value = atoi(argv[1]);
+        switch (value)
+        {
+            case 1:
+                isListOfObservers = true;
+                isSecure = false;
+                break;
+            case 2:
+                isListOfObservers = false;
+                isSecure = true;
+                break;
+            case 3:
+                isListOfObservers = true;
+                isSecure = true;
+                break;
+            case 4:
+                isSlowResponse = true;
+                break;
+            default:
+                PrintUsage();
+                break;
+       }
+     }
+    else
+    {
+        PrintUsage();
+        return -1;
+    }
+
+    // Create PlatformConfig object
+    PlatformConfig cfg {
+        OC::ServiceType::InProc,
+        OC::ModeType::Server,
+        "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+        0,         // Uses randomly available port
+        OC::QualityOfService::LowQos,
+        &ps
+    };
+
+    OCPlatform::Configure(cfg);
+    try
+    {
+        // Create the instance of the resource class
+        // (in this case instance of class 'MediaResource').
+        MediaResource myMedia;
+
+        // Invoke createResource function of class media.
+        myMedia.createResource();
+        cout << "Created resource." << std::endl;
+
+        // A condition variable will free the mutex it is given, then do a non-
+        // intensive block until 'notify' is called on it.  In this case, since we
+        // don't ever call cv.notify, this should be a non-processor intensive version
+        // of while(true);
+        std::mutex blocker;
+        std::condition_variable cv;
+        std::unique_lock<std::mutex> lock(blocker);
+        cout <<"Waiting" << std::endl;
+        cv.wait(lock, []{return false;});
+    }
+    catch(OCException &e)
+    {
+        cout << "OCException in main : " << e.what() << endl;
+    }
+
+    // No explicit call to stop the platform.
+    // When OCPlatform::destructor is invoked, internally we do platform cleanup
+
+    return 0;
+}
+
index 6feb473..59c0c32 100644 (file)
Binary files a/resource/examples/oic_svr_db_client.dat and b/resource/examples/oic_svr_db_client.dat differ
index 5052bd1..e4c9681 100644 (file)
@@ -8,38 +8,32 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
                         },\r
                         {\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/ad",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.ad"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        } ,\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
@@ -83,7 +77,7 @@
         "deviceuuid": "32323232-3232-3232-3232-323232323232",\r
         "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
         "rowneruuid": "32323232-3232-3232-3232-323232323232",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     },\r
     "cred": {\r
         "creds": [\r
diff --git a/resource/examples/oic_svr_db_client_directpairing.dat b/resource/examples/oic_svr_db_client_directpairing.dat
new file mode 100644 (file)
index 0000000..a4114f3
Binary files /dev/null and b/resource/examples/oic_svr_db_client_directpairing.dat differ
diff --git a/resource/examples/oic_svr_db_client_directpairing.json b/resource/examples/oic_svr_db_client_directpairing.json
new file mode 100644 (file)
index 0000000..6ef7755
--- /dev/null
@@ -0,0 +1,82 @@
+{\r
+    "acl": {\r
+        "aclist": {\r
+            "aces": [\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/res",\r
+                            "rel": "",\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
+                        },\r
+                        {\r
+                            "href": "/oic/d",\r
+                            "rel": "",\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
+                        },\r
+                        {\r
+                            "href": "/oic/p",\r
+                            "rel": "",\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
+                        }\r
+                    ],\r
+                    "permission": 2\r
+                },\r
+                {\r
+                    "subjectuuid": "*",\r
+                    "resources": [\r
+                        {\r
+                            "href": "/oic/sec/doxm",\r
+                            "rel": "",\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/pstat",\r
+                            "rel": "",\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/acl",\r
+                            "rel": "",\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
+                        {\r
+                            "href": "/oic/sec/cred",\r
+                            "rel": "",\r
+                            "rt": ["oic.r.cred"],\r
+                            "if": ["oic.if.baseline"]\r
+                        }\r
+                    ],\r
+                    "permission": 6\r
+                }\r
+            ]\r
+        },\r
+        "rowneruuid" : "64706169-7269-6e67-4465-765555494430"\r
+    },\r
+    "pstat": {\r
+        "isop": false,\r
+        "deviceuuid": "64706169-7269-6e67-4465-765555494430",\r
+        "rowneruuid": "64706169-7269-6e67-4465-765555494430",\r
+        "cm": 2,\r
+        "tm": 0,\r
+        "om": 3,\r
+        "sm": 3\r
+        },\r
+    "doxm": {\r
+        "oxms": [0],\r
+        "oxmsel": 0,\r
+        "sct": 1,\r
+        "owned": false,\r
+        "deviceuuid": "64706169-7269-6e67-4465-765555494430",\r
+        "devowneruuid": "",\r
+        "rowneruuid": "64706169-7269-6e67-4465-765555494430",\r
+        "x.com.samsung.dpc": false\r
+    }\r
+}\r
index 6834a79..4d883c4 100644 (file)
Binary files a/resource/examples/oic_svr_db_server.dat and b/resource/examples/oic_svr_db_server.dat differ
index 921cc9d..037efec 100644 (file)
@@ -8,38 +8,32 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
                         },\r
                         {\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/ad",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.ad"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        } ,\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
@@ -68,8 +62,8 @@
                         {\r
                             "href": "/a/light",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.core"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 6\r
@@ -95,7 +89,7 @@
         "deviceuuid": "31313131-3131-3131-3131-313131313131",\r
         "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
         "rowneruuid": "31313131-3131-3131-3131-313131313131",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     },\r
     "cred": {\r
         "creds": [\r
index 3755b57..328e1e7 100644 (file)
@@ -25,7 +25,7 @@
 #include <pthread.h>
 #include <mutex>
 #include <condition_variable>
-
+#include <getopt.h>
 #include "OCPlatform.h"
 #include "OCApi.h"
 
index e72c49d..5bb8b06 100644 (file)
 #include "OCPlatform.h"
 #include "OCApi.h"
 
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+#include "platform_features.h"
+
 using namespace OC;
 using namespace std;
 
@@ -141,9 +146,9 @@ public:
         }
     }
 
-    void addInterface(const std::string& interface) const
+    void addInterface(const std::string& iface) const
     {
-        OCStackResult result = OC::OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
+        OCStackResult result = OC::OCPlatform::bindInterfaceToResource(m_resourceHandle, iface);
         if (OC_STACK_OK != result)
         {
             cout << "Binding TypeName to Resource was unsuccessful\n";
index 07d55f0..c4aff50 100644 (file)
 
 // OCClient.cpp : Defines the entry point for the console application.
 //
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_PTHREAD_H
+#include <pthread.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <Windows.h>
+#endif
 #include <string>
 #include <map>
 #include <cstdlib>
-#include <pthread.h>
 #include <mutex>
 #include <condition_variable>
 #include "OCPlatform.h"
@@ -65,16 +73,12 @@ void onObserve(const HeaderOptions /*headerOptions*/, const OCRepresentation& re
 {
     try
     {
-        if(eCode == OC_STACK_OK && sequenceNumber != OC_OBSERVE_NO_OPTION)
+        if(eCode == OC_STACK_OK && sequenceNumber != -1)
         {
             if(sequenceNumber == OC_OBSERVE_REGISTER)
             {
                 std::cout << "Observe registration action is successful" << std::endl;
             }
-            else if(sequenceNumber == OC_OBSERVE_DEREGISTER)
-            {
-                std::cout << "Observe De-registration action is successful" << std::endl;
-            }
 
             std::cout << "OBSERVE RESULT:"<<std::endl;
             std::cout << "\tSequenceNumber: "<< sequenceNumber << std::endl;
@@ -99,9 +103,9 @@ void onObserve(const HeaderOptions /*headerOptions*/, const OCRepresentation& re
         }
         else
         {
-            if(sequenceNumber == OC_OBSERVE_NO_OPTION)
+            if(eCode == OC_STACK_OK)
             {
-                std::cout << "Observe registration or de-registration action is failed" << std::endl;
+                std::cout << "Observe registration failed or de-registration action failed/succeeded" << std::endl;
             }
             else
             {
@@ -469,7 +473,7 @@ int main(int argc, char* argv[]) {
         OC::ModeType::Both,
         "0.0.0.0",
         0,
-        OC::QualityOfService::LowQos,
+        OC::QualityOfService::HighQos,
         &ps
     };
 
index 86081f8..bb6283d 100644 (file)
 #include "OCPlatform.h"
 #include "OCApi.h"
 
+#if defined(HAVE_WINDOWS_H)
+#include <windows.h>
+#endif
+#include "platform_features.h"
+
 using namespace OC;
 
 struct dereference_compare
index 97a6074..13981cb 100644 (file)
 /// This sample provides steps to define an interface for a resource
 /// (properties and methods) and host this resource on the server.
 ///
-
 #include <functional>
 
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
+#endif
 #include <mutex>
 #include <condition_variable>
 
 #include "OCPlatform.h"
 #include "OCApi.h"
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+#include "platform_features.h"
 
 using namespace OC;
 using namespace std;
@@ -241,9 +249,9 @@ public:
         }
     }
 
-    void addInterface(const std::string& interface) const
+    void addInterface(const std::string& iface) const
     {
-        OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
+        OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, iface);
         if (OC_STACK_OK != result)
         {
             cout << "Binding TypeName to Resource was unsuccessful\n";
@@ -372,7 +380,12 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
                                                             m_interestedObservers.end());
             }
 
+#if defined(_WIN32)
+            DWORD threadId = 0;
+            HANDLE threadHandle = INVALID_HANDLE_VALUE;
+#else
             pthread_t threadId;
+#endif
 
             cout << "\t\trequestFlag : Observer\n";
             gObservation = 1;
@@ -382,7 +395,11 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
             // If we have not created the thread already, we will create one here.
             if(!startedThread)
             {
+#if defined(_WIN32)
+                threadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ChangeLightRepresentation, (void*)this, 0, &threadId);
+#else
                 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this);
+#endif
                 startedThread = 1;
             }
             ehResult = OC_EH_OK;
index f9e439e..607b45f 100644 (file)
 #include "OCPlatform.h"
 #include "OCApi.h"
 
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+#include "platform_features.h"
+
 using namespace OC;
 using namespace std;
 namespace PH = std::placeholders;
@@ -214,9 +219,9 @@ public:
         }
     }
 
-    void addInterface(const std::string& interface) const
+    void addInterface(const std::string& iface) const
     {
-        OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
+        OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, iface);
         if (OC_STACK_OK != result)
         {
             cout << "Binding TypeName to Resource was unsuccessful\n";
index 994858e..1eaaeba 100644 (file)
 
 #include "OCPlatform.h"
 #include "OCApi.h"
+
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+#include "platform_features.h"
+
 using namespace OC;
 
 static std::ostringstream requestURI;
diff --git a/resource/examples/winuiclient.cpp b/resource/examples/winuiclient.cpp
new file mode 100644 (file)
index 0000000..59e5d21
--- /dev/null
@@ -0,0 +1,439 @@
+/* ****************************************************************\r
+ *\r
+ * Copyright 2016 Intel Corporation All Rights Reserved.\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 <string>\r
+#include "winuiclient.h"\r
+#include <Windows.h>\r
+#include <Commctrl.h>\r
+#include <functional>\r
+\r
+extern int g_CurSliderVal;\r
+extern HWND hwndVolumeSlider, hwndVolumeExpectedLabel;\r
+using namespace WinUIClient;\r
+void LabelPrintf (HWND hwndEdit, TCHAR * szFormat, ...);\r
+\r
+WinUIClientApp::WinUIClientApp(OCPersistentStorage ps)\r
+    : persistentStorage(ps),\r
+      OBSERVE_TYPE_TO_USE(ObserveType::Observe)\r
+{\r
+\r
+}\r
+\r
+WinUIClientApp::~WinUIClientApp()\r
+{\r
+\r
+}\r
+\r
+void WinUIClientApp::Initialize()\r
+{\r
+    // Create PlatformConfig object\r
+    PlatformConfig cfg {\r
+        OC::ServiceType::InProc,\r
+        OC::ModeType::Both,\r
+        "0.0.0.0",\r
+        0,\r
+        OC::QualityOfService::LowQos,\r
+        &persistentStorage\r
+    };\r
+\r
+    OCPlatform::Configure(cfg);\r
+}\r
+\r
+void WinUIClientApp::Run()\r
+{\r
+    try\r
+    {\r
+        // makes it so that all boolean values are printed as 'true/false' in this stream\r
+        std::cout.setf(std::ios::boolalpha);\r
+        // Find all resources\r
+        std::ostringstream requestURI;// << "?rt=core.media";\r
+        std::string s = OC_RSRVD_WELL_KNOWN_URI;\r
+        requestURI << s;\r
+\r
+        OCPlatform::findResource("", requestURI.str(),\r
+                CT_DEFAULT, std::bind(&WinUIClientApp::foundResource, this, std::placeholders::_1));\r
+        std::cout<< "Finding Resource... " <<std::endl;\r
+\r
+        // Find resource is done twice so that we discover the original resources a second time.\r
+        // These resources will have the same uniqueidentifier (yet be different objects), so that\r
+        // we can verify/show the duplicate-checking code in foundResource(above);\r
+        OCPlatform::findResource("", requestURI.str(),\r
+                CT_DEFAULT, std::bind(&WinUIClientApp::foundResource, this, std::placeholders::_1));\r
+        std::cout<< "Finding Resource for second time..." << std::endl;\r
+\r
+    }catch(OCException& e)\r
+    {\r
+        std::cerr << "Exception in main: "<<e.what();\r
+    }\r
+}\r
+\r
+void WinUIClientApp::FindResources()\r
+{\r
+    std::ostringstream requestURI;\r
+    requestURI << OC_RSRVD_WELL_KNOWN_URI;// << "?rt=core.media";\r
+    OCPlatform::findResource("", requestURI.str(),\r
+                            CT_DEFAULT, std::bind(&WinUIClientApp::foundResource, this, std::placeholders::_1));\r
+}\r
+\r
+\r
+// Callback to found resources\r
+void WinUIClientApp::foundResource(std::shared_ptr<OCResource> resource)\r
+{\r
+    std::cout << "In foundResource\n";\r
+    std::string resourceURI;\r
+    std::string hostAddress;\r
+    try\r
+    {\r
+        {\r
+            std::lock_guard<std::mutex> lock(curResourceLock);\r
+            if (discoveredResources.find(resource->uniqueIdentifier()) == discoveredResources.end())\r
+            {\r
+                std::cout << "Found resource " << resource->uniqueIdentifier() <<\r
+                    " for the first time on server with ID: "<< resource->sid()<<std::endl;\r
+                discoveredResources[resource->uniqueIdentifier()] = resource;\r
+            }\r
+            else\r
+            {\r
+                std::cout<<"Found resource "<< resource->uniqueIdentifier() << " again!"<<std::endl;\r
+            }\r
+\r
+            if (curResource)\r
+            {\r
+                std::cout << "Found another resource, ignoring"<<std::endl;\r
+                return;\r
+            }\r
+        }\r
+\r
+        // Do some operations with resource object.\r
+        if (resource)\r
+        {\r
+            std::cout<<"DISCOVERED Resource:"<<std::endl;\r
+            // Get the resource URI\r
+            resourceURI = resource->uri();\r
+            std::cout << "\tURI of the resource: " << resourceURI << std::endl;\r
+\r
+            // Get the resource host address\r
+            hostAddress = resource->host();\r
+            std::cout << "\tHost address of the resource: " << hostAddress << std::endl;\r
+\r
+            // Get the resource types\r
+            std::cout << "\tList of resource types: " << std::endl;\r
+            for(auto &resourceTypes : resource->getResourceTypes())\r
+            {\r
+                std::cout << "\t\t" << resourceTypes << std::endl;\r
+            }\r
+\r
+            // Get the resource interfaces\r
+            std::cout << "\tList of resource interfaces: " << std::endl;\r
+            for(auto &resourceInterfaces : resource->getResourceInterfaces())\r
+            {\r
+                std::cout << "\t\t" << resourceInterfaces << std::endl;\r
+            }\r
+\r
+            if (resourceURI == "/a/media")\r
+            {\r
+                curResource = resource;\r
+                // Call a local function which will internally invoke get API on the resource pointer\r
+                this->GetMediaRepresentation();\r
+                this->BeginObserving();\r
+            }\r
+        }\r
+        else\r
+        {\r
+            // Resource is invalid\r
+            std::cout << "Resource is invalid" << std::endl;\r
+        }\r
+\r
+    }\r
+    catch(std::exception& e)\r
+    {\r
+        std::cerr << "Exception in foundResource: "<< e.what() << std::endl;\r
+    }\r
+}\r
+\r
+// Local function to get representation of media resource\r
+void WinUIClientApp::GetMediaRepresentation()\r
+{\r
+    if (curResource)\r
+    {\r
+        std::cout << "Getting Media Representation..."<<std::endl;\r
+        // Invoke resource's get API with the callback parameter\r
+\r
+        QueryParamsMap test;\r
+        curResource->get(test, std::bind(&WinUIClientApp::onGet, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));\r
+\r
+    }\r
+    else\r
+    {\r
+        std::cout << "No Current Resource to GetMediaRepresentation..."<<std::endl;\r
+    }\r
+}\r
+\r
+// Callback handler on GET request\r
+void WinUIClientApp::onGet(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)\r
+{\r
+    try\r
+    {\r
+        if (eCode == OC_STACK_OK)\r
+        {\r
+            std::cout << "GET request was successful" << std::endl;\r
+            std::cout << "Resource URI: " << rep.getUri() << std::endl;\r
+\r
+            rep.getValue("state", mymedia.m_state);\r
+            rep.getValue("volume", mymedia.m_volume);\r
+            rep.getValue("name", mymedia.m_name);\r
+\r
+            std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+            std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+            std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+\r
+            g_CurSliderVal = mymedia.m_volume;\r
+            SendMessage(hwndVolumeSlider, TBM_SETPOS, TRUE, g_CurSliderVal);\r
+            LabelPrintf(hwndVolumeExpectedLabel,"Volume: %i", g_CurSliderVal);\r
+\r
+        }\r
+        else\r
+        {\r
+            std::cout << "onGET Response error: " << eCode << std::endl;\r
+            std::exit(-1);\r
+        }\r
+    }\r
+    catch(std::exception& e)\r
+    {\r
+        std::cout << "Exception: " << e.what() << " in onGet" << std::endl;\r
+    }\r
+}\r
+\r
+// Local function to put a different state for this resource\r
+void WinUIClientApp::PutMediaRepresentation()\r
+{\r
+    if (curResource)\r
+    {\r
+        OCRepresentation rep;\r
+\r
+        std::cout << "Putting media representation..."<<std::endl;\r
+\r
+        rep.setValue("state", mymedia.m_state);\r
+        rep.setValue("volume", mymedia.m_volume);\r
+\r
+        // Invoke resource's put API with rep, query map and the callback parameter\r
+        curResource->put(rep, QueryParamsMap(), std::bind(&WinUIClientApp::onPut, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));\r
+    }\r
+}\r
+\r
+// callback handler on PUT request\r
+void WinUIClientApp::onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)\r
+{\r
+    try\r
+    {\r
+        if (eCode == OC_STACK_OK)\r
+        {\r
+            std::cout << "PUT request was successful" << std::endl;\r
+\r
+            rep.getValue("state", mymedia.m_state);\r
+            rep.getValue("volume", mymedia.m_volume);\r
+            rep.getValue("name", mymedia.m_name);\r
+\r
+            std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+            std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+            std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+\r
+        }\r
+        else\r
+        {\r
+            std::cout << "onPut Response error: " << eCode << std::endl;\r
+            std::exit(-1);\r
+        }\r
+    }\r
+    catch(std::exception& e)\r
+    {\r
+        std::cout << "Exception: " << e.what() << " in onPut" << std::endl;\r
+    }\r
+}\r
+\r
+// Local function to put a different state for this resource\r
+void WinUIClientApp::PostMediaRepresentation()\r
+{\r
+    if (curResource)\r
+    {\r
+        OCRepresentation rep;\r
+\r
+        std::cout << "Posting media representation..."<<std::endl;\r
+\r
+        rep.setValue("state", mymedia.m_state);\r
+        rep.setValue("volume", mymedia.m_volume);\r
+\r
+        // Invoke resource's post API with rep, query map and the callback parameter\r
+        curResource->post(rep, QueryParamsMap(), std::bind(&WinUIClientApp::onPost, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));\r
+    }\r
+}\r
+\r
+void WinUIClientApp::onPost(const HeaderOptions& /*headerOptions*/,\r
+        const OCRepresentation& rep, const int eCode)\r
+{\r
+    try\r
+    {\r
+        if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED)\r
+        {\r
+            std::cout << "POST request was successful" << std::endl;\r
+\r
+            if (rep.hasAttribute("createduri"))\r
+            {\r
+                std::cout << "\tUri of the created resource: "\r
+                    << rep.getValue<std::string>("createduri") << std::endl;\r
+            }\r
+            else\r
+            {\r
+                rep.getValue("state", mymedia.m_state);\r
+                rep.getValue("volume", mymedia.m_volume);\r
+                rep.getValue("name", mymedia.m_name);\r
+\r
+                std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+                std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+                std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+            }\r
+\r
+        }\r
+        else\r
+        {\r
+            std::cout << "onPost Response error: " << eCode << std::endl;\r
+            std::exit(-1);\r
+        }\r
+    }\r
+    catch (std::exception& e)\r
+    {\r
+        std::cout << "Exception: " << e.what() << " in onPost" << std::endl;\r
+    }\r
+}\r
+\r
+void WinUIClientApp::onPost2(const HeaderOptions& /*headerOptions*/,\r
+        const OCRepresentation& rep, const int eCode)\r
+{\r
+    try\r
+    {\r
+        if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED)\r
+        {\r
+            std::cout << "POST request was successful" << std::endl;\r
+\r
+            if (rep.hasAttribute("createduri"))\r
+            {\r
+                std::cout << "\tUri of the created resource: "\r
+                    << rep.getValue<std::string>("createduri") << std::endl;\r
+            }\r
+            else\r
+            {\r
+                rep.getValue("state", mymedia.m_state);\r
+                rep.getValue("volume", mymedia.m_volume);\r
+                rep.getValue("name", mymedia.m_name);\r
+\r
+                std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+                std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+                std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+            }\r
+\r
+        }\r
+        else\r
+        {\r
+            std::cout << "onPost2 Response error: " << eCode << std::endl;\r
+            std::exit(-1);\r
+        }\r
+    }\r
+    catch(std::exception& e)\r
+    {\r
+        std::cout << "Exception: " << e.what() << " in onPost2" << std::endl;\r
+    }\r
+\r
+}\r
+\r
+void WinUIClientApp::onObserve(const HeaderOptions /*headerOptions*/, const OCRepresentation& rep,\r
+                    const int& eCode, const int& sequenceNumber)\r
+{\r
+    try\r
+    {\r
+        if (eCode == OC_STACK_OK && sequenceNumber != OC_OBSERVE_NO_OPTION)\r
+        {\r
+            if (sequenceNumber == OC_OBSERVE_REGISTER)\r
+            {\r
+                std::cout << "Observe registration action is successful" << std::endl;\r
+            }\r
+            else if (sequenceNumber == OC_OBSERVE_DEREGISTER)\r
+            {\r
+                std::cout << "Observe De-registration action is successful" << std::endl;\r
+            }\r
+\r
+            std::cout << "OBSERVE RESULT:"<<std::endl;\r
+            std::cout << "\tSequenceNumber: "<< sequenceNumber << std::endl;\r
+            rep.getValue("state", mymedia.m_state);\r
+            rep.getValue("volume", mymedia.m_volume);\r
+            rep.getValue("name", mymedia.m_name);\r
+\r
+            std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+            std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+            std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+\r
+            g_CurSliderVal = mymedia.m_volume;\r
+            SendMessage(hwndVolumeSlider, TBM_SETPOS, TRUE, g_CurSliderVal);\r
+            LabelPrintf(hwndVolumeExpectedLabel,"Volume: %i", g_CurSliderVal);\r
+        }\r
+        else\r
+        {\r
+            if (sequenceNumber == OC_OBSERVE_NO_OPTION)\r
+            {\r
+                std::cout << "Observe registration or de-registration action is failed" << std::endl;\r
+            }\r
+            else\r
+            {\r
+                std::cout << "onObserve Response error: " << eCode << std::endl;\r
+                std::exit(-1);\r
+            }\r
+        }\r
+    }\r
+    catch (std::exception& e)\r
+    {\r
+        std::cout << "Exception: " << e.what() << " in onObserve" << std::endl;\r
+    }\r
+\r
+}\r
+\r
+void WinUIClientApp::BeginObserving()\r
+{\r
+    if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)\r
+        std::cout << std::endl << "Observe is used." << std::endl << std::endl;\r
+    else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)\r
+        std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl;\r
+\r
+    curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), std::bind(&WinUIClientApp::onObserve, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));\r
+}\r
+\r
+void WinUIClientApp::CancelObserving()\r
+{\r
+    std::cout<<"Cancelling Observe..."<<std::endl;\r
+    OCStackResult result = curResource->cancelObserve();\r
+}\r
+\r
+std::shared_ptr<OCResource> WinUIClientApp::GetResource()\r
+{\r
+    return curResource;\r
+}\r
+\r
+int WinUIClientApp::observe_count()\r
+{\r
+    static int oc = 0;\r
+    return ++oc;\r
+}\r
+\r
diff --git a/resource/examples/winuiclient.h b/resource/examples/winuiclient.h
new file mode 100644 (file)
index 0000000..b052e4e
--- /dev/null
@@ -0,0 +1,89 @@
+/* ****************************************************************
+ *
+ * Copyright 2016 Intel Corporation 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 WINUICLIENT_H_
+#define WINUICLIENT_H_
+
+#include <memory>
+#include <mutex>
+#include <map>
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "OCResource.h"
+
+using namespace OC;
+namespace WinUIClient{
+
+    class Media
+    {
+        public:
+
+            bool m_state;
+            int m_volume;
+            std::string m_name;
+
+            Media() : m_state(false), m_volume(0), m_name("")
+            {
+            }
+    };
+
+    class WinUIClientApp
+    {
+        public:
+            WinUIClientApp(OCPersistentStorage ps);
+            ~WinUIClientApp();
+
+            void Initialize();
+            void Run();
+            void FindResources();
+            void GetMediaRepresentation();
+            void PutMediaRepresentation();
+            void PostMediaRepresentation();
+            void BeginObserving();
+            void CancelObserving();
+
+            std::shared_ptr<OCResource> GetResource();
+            Media GetMedia(){return mymedia;}
+            void SetMedia(bool state, int volume){mymedia.m_state = state; mymedia.m_volume=volume;}
+            bool observing;
+
+        private:
+            void foundResource(std::shared_ptr<OCResource> resource);
+            void onGet(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode);
+            void onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode);
+            void onPost(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode);
+            void onPost2(const HeaderOptions& /*headerOptions*/,const OCRepresentation& rep, const int eCode);
+            void onObserve(const HeaderOptions /*headerOptions*/, const OCRepresentation& rep, const int& eCode, const int& sequenceNumber);
+        private:
+            int observe_count();
+
+        private:
+            typedef std::map<OCResourceIdentifier, std::shared_ptr<OCResource>> DiscoveredResourceMap;
+
+            OCPersistentStorage persistentStorage;
+            Media mymedia;
+            DiscoveredResourceMap discoveredResources;
+            std::shared_ptr<OCResource> curResource;
+            ObserveType OBSERVE_TYPE_TO_USE;
+            std::mutex curResourceLock;
+    };
+
+}
+
+#endif
+
diff --git a/resource/examples/winuiclientgui.cpp b/resource/examples/winuiclientgui.cpp
new file mode 100644 (file)
index 0000000..596bb4e
--- /dev/null
@@ -0,0 +1,370 @@
+/* ****************************************************************
+ *
+ * Copyright 2016 Intel Corporation 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 <string>
+#include "winuiclient.h"
+
+#include <Windows.h>
+#include <Commctrl.h>
+
+#define ID_TRACKBAR             0x50505
+#define ID_BUTTONPLAYPAUSE      0xFFF0
+#define ID_BUTTONFIND           0xFFF1
+#define ID_BUTTONGET            0xFFF2
+#define ID_BUTTONPUT            0xFFF3
+#define ID_BUTTONPOST           0xFFF4
+#define ID_BUTTONBEGINOBSERVE   0xFFF5
+#define ID_BUTTONCANCELOBSERVE  0xFFF6
+
+int g_CurSliderVal = 0;
+
+HWND hwnd, icon_button, hwndVolumeSlider, hwndVolumeExpectedLabel;
+HWND hwndButtonPlayPause, hwndButtonFind, hwndButtonGet, hwndButtonPut, hwndButtonPost, hwndButtonBeginObserve, hwndButtonCancelObserve;
+HINSTANCE hInstance, g_hinstTrackBar, g_hinstVolumeSlider, g_hinstVolumeLabel;
+HANDLE Timer, Thread;
+HICON hIcon1;
+HBRUSH g_BkgndBrush;
+
+WinUIClient::WinUIClientApp* app = NULL;
+
+LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
+void LabelPrintf (HWND hwndEdit, TCHAR * szFormat, ...);
+HWND WINAPI CreateTrackbar(HWND parent, int x, int y, int w, int h,UINT iMin, UINT iMax, UINT iSelMin, UINT iSelMax);
+HWND WINAPI CreateLabel(HWND parent, LPCTSTR lpText, int x, int y, int w, int h);
+HWND WINAPI CreateButton(HWND parent, UINT_PTR id, LPCTSTR caption, int x, int y, int w, int h);
+
+FILE* client_open(const char* /*path*/, const char *mode)
+{
+    return fopen("./oic_svr_db_client.dat", mode);
+}
+
+int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
+            LPSTR lpCmdLine, int nCmdShow )
+{
+    MSG msg;
+    WNDCLASS wc = {sizeof(WNDCLASS)};
+    wc.lpszClassName = TEXT( "Static Control" );
+    wc.hInstance     = hInstance ;
+    wc.hbrBackground = GetSysColorBrush(COLOR_MENU);
+    wc.lpfnWndProc   = WndProc;
+    wc.hIcon         = LoadIcon (NULL, IDI_APPLICATION);
+    wc.hCursor = LoadCursor (NULL, IDC_ARROW);
+
+    RegisterClass(&wc);
+    hwnd = CreateWindow( wc.lpszClassName, TEXT("IoTivity Media Client - Windows UI"),
+                   WS_OVERLAPPEDWINDOW ^ WS_THICKFRAME,
+                   100, 100, 275, 170, 0, 0, hInstance, 0);
+
+    InitCommonControls(); // loads common control's DLL
+
+    hwndVolumeSlider =
+             CreateTrackbar(hwnd,
+                            10,10,
+                            170,40,
+                            0,100,
+                            0,0);
+    hwndVolumeExpectedLabel =
+                CreateLabel(hwnd,
+                            "Expected Volume",
+                            10,50,
+                            240,30);
+
+    LabelPrintf(hwndVolumeExpectedLabel,
+                "Expected Volume: %i",
+                0);
+
+    hwndButtonPlayPause =
+                CreateButton(hwnd,
+                             ID_BUTTONPLAYPAUSE,
+                             "PlayPause",
+                             180,10,
+                             80,35);
+
+    hwndButtonFind =
+                CreateButton(hwnd,
+                             ID_BUTTONFIND,
+                             "Find",
+                             10,75,
+                             64,25);
+
+    hwndButtonGet =
+                CreateButton(hwnd,
+                             ID_BUTTONGET,
+                             "Get",
+                             10,105,
+                             64,25);
+
+    hwndButtonPut =
+                CreateButton(hwnd,
+                             ID_BUTTONPUT,
+                             "Put",
+                             80,75,
+                             64,25);
+
+    hwndButtonPost =
+                CreateButton(hwnd,
+                             ID_BUTTONPOST,
+                             "Post",
+                             80,105,
+                             64,25);
+    hwndButtonBeginObserve =
+                CreateButton(hwnd,
+                             ID_BUTTONBEGINOBSERVE,
+                             "Bgn Obs",
+                             150,75,
+                             64,25);
+    hwndButtonCancelObserve =
+                CreateButton(hwnd,
+                             ID_BUTTONCANCELOBSERVE,
+                             "Cncl Obs",
+                             150,105,
+                             64,25);
+
+
+    ShowWindow(hwnd, nCmdShow);
+    UpdateWindow(hwnd);
+
+    while (GetMessage(&msg, NULL, 0, 0))
+    {
+        TranslateMessage(&msg);
+        DispatchMessage(&msg);
+    }
+
+    return (int) msg.wParam;
+}
+
+LRESULT
+CALLBACK
+WndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
+{
+    HDC hDC;
+    RECT rect;
+    WinUIClient::Media myMedia;
+
+    switch(msg){
+      case WM_HSCROLL:
+        switch (LOWORD(wParam)) {
+            case TB_ENDTRACK:
+                g_CurSliderVal = SendMessage(hwndVolumeSlider, TBM_GETPOS, 0, 0);
+                LabelPrintf(hwndVolumeExpectedLabel,"Volume: %i", g_CurSliderVal);
+
+                myMedia = app->GetMedia();
+                myMedia.m_volume = g_CurSliderVal;
+                app->SetMedia(myMedia.m_state, myMedia.m_volume);
+                app->PostMediaRepresentation();
+                break;
+        }
+        break;
+      case WM_CREATE:
+          {
+              hIcon1 = LoadIcon (NULL, IDI_WARNING);
+              SendMessage(icon_button,BM_SETIMAGE,IMAGE_ICON,(LPARAM)hIcon1);
+              GetClientRect(hwnd, &rect);
+              g_BkgndBrush = GetSysColorBrush(COLOR_MENU);
+
+              OCPersistentStorage ps = {client_open, fread, fwrite, fclose, unlink };
+              app = new WinUIClient::WinUIClientApp(ps);
+              app->Initialize();
+              app->Run();
+          }
+          break;
+      case WM_DESTROY:
+
+          delete app;
+
+          PostQuitMessage(0);
+          break;
+      case WM_ERASEBKGND:
+          GetClientRect(hwnd, &rect);
+          hDC = GetDC(hwnd);
+          SelectObject((HDC)wParam, g_BkgndBrush);
+          Rectangle((HDC)hDC, rect.left, rect.top, rect.right, rect.bottom);
+          ReleaseDC(hwnd, hDC);
+          break;
+      case WM_SIZE:
+          break;
+      case WM_RBUTTONDOWN:
+      case WM_LBUTTONDOWN:
+          break;
+      case WM_MOUSELEAVE:
+      case WM_RBUTTONUP:
+      case WM_LBUTTONUP:
+          break;
+      case WM_COMMAND:
+        if (HIWORD(wParam) == BN_CLICKED)
+        {
+
+            switch (LOWORD(wParam))
+            {
+                case ID_BUTTONPLAYPAUSE:
+                    myMedia = app->GetMedia();
+
+                    // HACK: We are using m_state in a stateless way.
+                    // True means "toggle".  The server does not have state
+                    // knowledge about whether or not media is playing on the
+                    // system.  It's dumb and hits the "PlayPause" key on the
+                    // keyboard.
+                    //
+                    myMedia.m_state = true;
+                    app->SetMedia(myMedia.m_state, myMedia.m_volume);
+                    myMedia.m_state = false;
+
+                    app->PutMediaRepresentation();
+                    break;
+                case ID_BUTTONFIND:
+                    app->FindResources();
+                    break;
+                case ID_BUTTONGET:
+                    app->GetMediaRepresentation();
+                    break;
+                case ID_BUTTONPUT:
+                    myMedia = app->GetMedia();
+                    myMedia.m_volume = g_CurSliderVal;
+                    app->SetMedia(myMedia.m_state, myMedia.m_volume);
+                    app->PutMediaRepresentation();
+                    break;
+                case ID_BUTTONPOST:
+                    myMedia = app->GetMedia();
+                    myMedia.m_volume = g_CurSliderVal;
+                    app->SetMedia(myMedia.m_state, myMedia.m_volume);
+                    app->PostMediaRepresentation();
+                    break;
+                case ID_BUTTONBEGINOBSERVE:
+                    app->BeginObserving();
+                    break;
+                case ID_BUTTONCANCELOBSERVE:
+                    app->CancelObserving();
+                    break;
+            }
+        }
+        break;
+      default:
+          return DefWindowProc(hwnd, msg, wParam, lParam);
+    }
+
+    return 0;
+}
+
+#define GWL_HINSTANCE -6
+HWND WINAPI CreateButton(HWND parent,
+                            UINT_PTR id,
+                            LPCTSTR caption    ,
+                            int x,
+                            int y,
+                            int w,
+                            int h
+                            )
+{
+    HWND hwndButton = CreateWindow(
+        "BUTTON",  // Predefined class; Unicode assumed
+        caption,      // Button text
+        WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  // Styles
+        x,         // x position
+        y,         // y position
+        w,        // Button width
+        h,        // Button height
+        parent,     // Parent window
+        (HMENU)id,       // No menu.
+        (HINSTANCE)GetWindowLongPtr(parent, GWL_HINSTANCE),
+        NULL);      // Pointer not needed.
+
+    return hwndButton;
+}
+
+HWND WINAPI CreateLabel(
+    HWND parent,  // handle of parent window
+    LPCTSTR lpText,
+    int x,
+    int y,
+    int w,
+    int h
+)
+{
+   HWND hwndPowerLabel  = CreateWindow("static", "ST_U",
+                                      WS_CHILD | WS_VISIBLE | WS_TABSTOP,
+                                      x, y, w, h,
+                                      parent, (HMENU)(501),
+                                      (HINSTANCE)GetWindowLongPtr(parent, GWL_HINSTANCE),
+                                      NULL);
+   SetWindowText(hwndPowerLabel, lpText);
+   return hwndPowerLabel;
+}
+
+// CreateTrackbar - creates and initializes a trackbar.
+//
+// Global variable
+//     g_hinstTrackBar - instance handle
+//
+HWND WINAPI CreateTrackbar(
+    HWND parent,  // handle of dialog box (parent window)
+    int x,
+    int y,
+    int w,
+    int h,
+    UINT iMin,     // minimum value in trackbar range
+    UINT iMax,     // maximum value in trackbar range
+    UINT iSelMin,  // minimum value in trackbar selection
+    UINT iSelMax)  // maximum value in trackbar selection
+{
+    HWND hwndVolumeSlider = CreateWindowEx(
+        0,                              // no extended styles
+        TRACKBAR_CLASS,                 // class name
+        "Trackbar Control",             // title (caption)
+        WS_CHILD |
+        WS_VISIBLE |
+        TBS_AUTOTICKS |
+        TBS_ENABLESELRANGE,             // style
+        x,y,w,h,                        // position ,size
+        parent,                        // parent window
+        (HMENU)ID_TRACKBAR,             // control identifier
+        (HINSTANCE)GetWindowLongPtr(parent, GWL_HINSTANCE),// instance
+        NULL                            // no WM_CREATE parameter
+        );
+
+    SendMessage(hwndVolumeSlider, TBM_SETRANGE,
+        (WPARAM) TRUE,                  // redraw flag
+        (LPARAM) MAKELONG(iMin, iMax)); // min. & max. positions
+
+    SendMessage(hwndVolumeSlider, TBM_SETPAGESIZE,
+        0, (LPARAM) 4);                 // new page size
+
+    SendMessage(hwndVolumeSlider, TBM_SETSEL,
+        (WPARAM) FALSE,                 // redraw flag
+        (LPARAM) MAKELONG(iSelMin, iSelMax));
+
+    SendMessage(hwndVolumeSlider, TBM_SETPOS,
+        (WPARAM) TRUE,                  // redraw flag
+        (LPARAM) iSelMin);
+
+    SetFocus(hwndVolumeSlider);
+
+    return hwndVolumeSlider;
+}
+
+void LabelPrintf (HWND hwndEdit, TCHAR * szFormat, ...)
+{
+     TCHAR   szBuffer [1024] ;
+     va_list pArgList ;
+
+     va_start (pArgList, szFormat) ;
+     wvsprintf (szBuffer, szFormat, pArgList) ;
+     va_end (pArgList) ;
+
+     SetWindowText(hwndEdit, szBuffer);
+}
+
index 2bfb10b..5b9ca83 100644 (file)
@@ -100,43 +100,43 @@ namespace OC
     template<>
     struct AttributeTypeConvert<NullType>
     {
-        constexpr static AttributeType type = AttributeType::Null;
+        BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Null;
     };
 
     template<>
     struct AttributeTypeConvert<int>
     {
-        constexpr static AttributeType type = AttributeType::Integer;
+        BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Integer;
     };
 
     template<>
     struct AttributeTypeConvert<double>
     {
-        constexpr static AttributeType type = AttributeType::Double;
+        BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Double;
     };
 
     template<>
     struct AttributeTypeConvert<bool>
     {
-        constexpr static AttributeType type = AttributeType::Boolean;
+        BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Boolean;
     };
 
     template<>
     struct AttributeTypeConvert<std::string>
     {
-        constexpr static AttributeType type = AttributeType::String;
+        BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::String;
     };
 
     template<>
     struct AttributeTypeConvert<OCRepresentation>
     {
-        constexpr static AttributeType type = AttributeType::OCRepresentation;
+        BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::OCRepresentation;
     };
 
     template<>
     struct AttributeTypeConvert<std::vector<uint8_t>>
     {
-        constexpr static AttributeType type = AttributeType::Binary;
+        BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Binary;
     };
 
     std::ostream& operator << (std::ostream& os, const AttributeType at);
index 0a69743..9872f5d 100644 (file)
@@ -49,6 +49,24 @@ namespace OC
         */
         OCStackResult setNetworkMonitorHandler(AdapterChangedCallback adapterHandler,
                                                ConnectionChangedCallback connectionHandler);
+
+        /**
+        * Set port number to use.
+        * @param adapter transport adapter type to assign the specified port number.
+        * @param flag transport flag information.
+        * @param port the specified port number to use.
+        * @return Returns ::OC_STACK_OK if success.
+        */
+        OCStackResult setPortNumberToAssign(OCTransportAdapter adapter,
+                                            OCTransportFlags flag, uint16_t port);
+
+        /**
+        * Get the assigned port number.
+        * @param adapter transport adapter type to get the opened port number.
+        * @param flag   transport flag information.
+        * @return Returns currently assigned port number.
+        */
+        uint16_t getAssignedPortNumber(OCTransportAdapter adapter, OCTransportFlags flag);
     }
 }
 
index 6a3d525..0cbfa53 100644 (file)
@@ -23,7 +23,6 @@
 
 #include <memory>
 #include <string>
-
 #include <OCApi.h>
 
 namespace OC
@@ -111,6 +110,14 @@ namespace OC
 
         virtual OCStackResult GetDefaultQos(QualityOfService& qos) = 0;
 
+        virtual OCStackResult FindDirectPairingDevices(unsigned short waittime,
+                        GetDirectPairedCallback& callback) = 0;
+
+        virtual OCStackResult GetDirectPairedDevices(GetDirectPairedCallback& callback) = 0;
+
+        virtual OCStackResult DoDirectPairing(std::shared_ptr<OCDirectPairing> peer, const OCPrm_t& pmSel,
+                const std::string& pinNumber, DirectPairingCallback& resultCallback) = 0;
+
         virtual ~IClientWrapper(){}
     };
 }
index 33d3e22..c13edb1 100644 (file)
@@ -92,6 +92,13 @@ namespace OC
             ObserveCallback callback;
             ObserveContext(ObserveCallback cb) : callback(cb){}
         };
+
+        struct DirectPairingContext
+        {
+            DirectPairingCallback callback;
+            DirectPairingContext(DirectPairingCallback cb) : callback(cb){}
+
+        };
     }
 
     class InProcClientWrapper : public IClientWrapper
@@ -161,12 +168,23 @@ namespace OC
 
         virtual OCStackResult UnsubscribePresence(OCDoHandle handle);
         OCStackResult GetDefaultQos(QualityOfService& QoS);
+
+
+        virtual OCStackResult FindDirectPairingDevices(unsigned short waittime,
+                       GetDirectPairedCallback& callback);
+
+        virtual OCStackResult GetDirectPairedDevices(GetDirectPairedCallback& callback);
+
+        virtual OCStackResult DoDirectPairing(std::shared_ptr<OCDirectPairing> peer, const OCPrm_t& pmSel,
+                const std::string& pinNumber, DirectPairingCallback& resultCallback);
+
     private:
         void listeningFunc();
         std::string assembleSetResourceUri(std::string uri, const QueryParamsMap& queryParams);
         OCPayload* assembleSetResourcePayload(const OCRepresentation& attributes);
         OCHeaderOption* assembleHeaderOptions(OCHeaderOption options[],
            const HeaderOptions& headerOptions);
+        void convert(const OCDPDev_t *list, PairedDevices& dpList);
         std::thread m_listeningThread;
         bool m_threadRun;
         std::weak_ptr<std::recursive_mutex> m_csdkLock;
index d124502..d2ac74a 100644 (file)
@@ -27,6 +27,9 @@
 #include <map>
 #include <memory>
 #include <iterator>
+#if defined(_MSC_VER)
+#include <functional>
+#endif
 
 #include "octypes.h"
 #include "OCHeaderOption.h"
@@ -41,10 +44,14 @@ namespace OC
     class OCResource;
     class OCResourceRequest;
     class OCResourceResponse;
+    class OCDirectPairing;
 } // namespace OC
 
 namespace OC
 {
+#if defined(_MSC_VER)
+    extern std::ostream& oclog();
+#else
     typedef boost::iostreams::stream<OC::oc_log_stream>     log_target_t;
 
     namespace detail
@@ -65,7 +72,7 @@ namespace OC
     {
         return detail::oclog_target();
     };
-
+#endif
 } // namespace OC
 
 namespace OC
@@ -249,6 +256,8 @@ namespace OC
     // Used in GET, PUT, POST methods on links to other remote resources of a group.
     const std::string GROUP_INTERFACE = "oic.mi.grp";
 
+    //Typedef for list direct paired devices
+    typedef std::vector<std::shared_ptr<OCDirectPairing>> PairedDevices;
 
     typedef std::function<void(std::shared_ptr<OCResource>)> FindCallback;
 
@@ -277,6 +286,11 @@ namespace OC
 
     typedef std::function<void(const HeaderOptions&,
                                 const OCRepresentation&, const int, const int)> ObserveCallback;
+
+    typedef std::function<void(std::shared_ptr<OCDirectPairing>, OCStackResult)> DirectPairingCallback;
+
+    typedef std::function<void(const PairedDevices&)> GetDirectPairedCallback;
+
 } // namespace OC
 
 #endif
diff --git a/resource/include/OCDirectPairing.h b/resource/include/OCDirectPairing.h
new file mode 100644 (file)
index 0000000..3f27b83
--- /dev/null
@@ -0,0 +1,69 @@
+//******************************************************************
+//
+// 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_DIRECT_PAIRING_H_
+#define OC_DIRECT_PAIRING_H_
+#include <OCApi.h>
+
+namespace OC
+{
+    class OCDirectPairing
+    {
+        public:
+            OCDirectPairing(OCDPDev_t *ptr);
+            /**
+             * Function to get the host address of direct pairing device.
+             *
+             * @return Returns host address in the format
+             *           <coaps>:IP:securePort
+             */
+            std::string getHost();
+
+            /**
+             * Function to get the device ID of the direct pairing device.
+             *
+             * @return Returns device ID (UUID)
+             */
+            std::string getDeviceID();
+
+            /**
+             * Function to get the pairing methods supported by direct pairing device.
+             *
+             * @return Returns vector of pairing methods supported.
+             *   DP_NOT_ALLOWED
+             *   DP_PRE_CONFIGURED
+             *   DP_RANDOM_PIN
+             */
+            std::vector<OCPrm_t> getPairingMethods();
+
+            /**
+             * Function to get the connectivity Type.
+             *
+             * @return Returns connectivity Type
+             */
+            OCConnectivityType getConnType();
+
+            OCDPDev_t* getDev();
+
+        private:
+            OCDPDev_t *m_devPtr;
+    };
+}
+#endif //OC_DIRECT_PAIRING_H_
index 519da78..78f9029 100644 (file)
@@ -80,11 +80,25 @@ namespace OC
 
             OCHeaderOption(const OCHeaderOption&) = default;
 
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+            OCHeaderOption(OCHeaderOption&& o)
+            {
+                std::memmove(this, &o, sizeof(o));
+            }
+#else
             OCHeaderOption(OCHeaderOption&&) = default;
+#endif
 
             OCHeaderOption& operator=(const OCHeaderOption&) = default;
 
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+            OCHeaderOption& operator=(OCHeaderOption&& o)
+            {
+                std::memmove(this, &o, sizeof(o));
+            }
+#else
             OCHeaderOption& operator=(OCHeaderOption&&) = default;
+#endif
 
             /**
             * API to get Option ID
index 2828b9e..37c4b54 100644 (file)
@@ -523,45 +523,45 @@ namespace OC
                         SubscribeCallback presenceHandler);
 
         /**
-        * unsubscribes from a previously subscribed server's presence events. Note that
-        * you may for a short time still receive events from the server since it may take time
-        * for the unsubscribe to take effect.
-        *
-        * @param presenceHandle the handle object provided by the subscribePresence call that
-        *               identifies this subscription.
-        *
-        * @return Returns ::OC_STACK_OK if success.
-        */
+         * unsubscribes from a previously subscribed server's presence events. Note that
+         * you may for a short time still receive events from the server since it may take time
+         * for the unsubscribe to take effect.
+         *
+         * @param presenceHandle the handle object provided by the subscribePresence call that
+         *               identifies this subscription.
+         *
+         * @return Returns ::OC_STACK_OK if success.
+         */
         OCStackResult unsubscribePresence(OCPresenceHandle presenceHandle);
 
         /**
-        * Creates a resource proxy object so that get/put/observe functionality
-        * can be used without discovering the object in advance.  Note that the
-        * consumer of this method needs to provide all of the details required to
-        * correctly contact and observe the object. If the consumer lacks any of
-        * this information, they should discover the resource object normally.
-        * Additionally, you can only create this object if OCPlatform was initialized
-        * to be a Client or Client/Server.  Otherwise, this will return an empty
-        * shared ptr.
-        *
-        * @param host a string containing a resolvable host address of the server
-        *           holding the resource. Currently this should be in the format
-        *           coap://address:port, though in the future, we expect this to
-        *           change to //address:port
-        *
-        * @param uri the rest of the resource's URI that will permit messages to be
-        *           properly routed.  Example: /a/light
-        *
-        * @param connectivityType ::OCConnectivityType type of connectivity indicating the
-        *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
-        *
-        * @param isObservable a boolean containing whether the resource supports observation
-        *
-        * @param resourceTypes a collection of resource types implemented by the resource
-        *
-        * @param interfaces a collection of interfaces that the resource supports/implements
-        * @return OCResource::Ptr a shared pointer to the new resource object
-        */
+         * Creates a resource proxy object so that get/put/observe functionality
+         * can be used without discovering the object in advance.  Note that the
+         * consumer of this method needs to provide all of the details required to
+         * correctly contact and observe the object. If the consumer lacks any of
+         * this information, they should discover the resource object normally.
+         * Additionally, you can only create this object if OCPlatform was initialized
+         * to be a Client or Client/Server.  Otherwise, this will return an empty
+         * shared ptr.
+         *
+         * @param host a string containing a resolvable host address of the server
+         *           holding the resource. Currently this should be in the format
+         *           coap://address:port, though in the future, we expect this to
+         *           change to //address:port
+         *
+         * @param uri the rest of the resource's URI that will permit messages to be
+         *           properly routed.  Example: /a/light
+         *
+         * @param connectivityType ::OCConnectivityType type of connectivity indicating the
+         *                           interface. Example: OC_WIFI, OC_ETHERNET, OC_ALL
+         *
+         * @param isObservable a boolean containing whether the resource supports observation
+         *
+         * @param resourceTypes a collection of resource types implemented by the resource
+         *
+         * @param interfaces a collection of interfaces that the resource supports/implements
+         * @return OCResource::Ptr a shared pointer to the new resource object
+         */
         OCResource::Ptr constructResourceObject(const std::string& host,
                         const std::string& uri,
                         OCConnectivityType connectivityType, bool isObservable,
@@ -569,14 +569,48 @@ namespace OC
                         const std::vector<std::string>& interfaces);
 
         /**
-        * Allows application entity handler to send response to an incoming request.
-        *
-        * @param pResponse OCResourceResponse pointer that will permit to set values related
-        * to resource response.
-        *
-        * @return Returns ::OC_STACK_OK if success.
-        */
+         * Allows application entity handler to send response to an incoming request.
+         *
+         * @param pResponse OCResourceResponse pointer that will permit to set values related
+         * to resource response.
+         *
+         * @return Returns ::OC_STACK_OK if success.
+         */
         OCStackResult sendResponse(const std::shared_ptr<OCResourceResponse> pResponse);
+
+        /**
+         * Find all the Direct Pairing capable devices.
+         *
+         * @param waittime timeoutbefore the callback is called
+         * @param callback function to callback with discovered devices after timeout
+         *
+         * @return Returns ::OC_STACK_OK if success
+         */
+        OCStackResult findDirectPairingDevices(unsigned short waittime,
+                                     GetDirectPairedCallback callback);
+
+        /**
+         * Get all the Direct paired devices.
+         *
+         * @param callback function to callback with the list of paired devices
+         *
+         * @return Returns ::OC_STACK_OK if success
+         */
+        OCStackResult getDirectPairedDevices(GetDirectPairedCallback callback);
+
+        /**
+         * Perform the Direct Pairing with the selected peer device
+         *
+         * @param peer device to direct pair with
+         * @param pmSel Selected pairing method
+         * @param pinNumber pin to validate peer & perform the direct pairing
+         * @param resultCallback callback function that will get the result of the operation
+         *
+         * @return Returns ::OC_STACK_OK if success
+         */
+        OCStackResult doDirectPairing(std::shared_ptr<OCDirectPairing> peer, OCPrm_t pmSel,
+                                     const std::string& pinNumber,
+                                     DirectPairingCallback resultCallback);
     }
 }
 
index 45441fe..51217f0 100644 (file)
@@ -37,6 +37,7 @@
 #include "OCResourceRequest.h"
 #include "OCResourceResponse.h"
 #include "OCRepresentation.h"
+#include "OCDirectPairing.h"
 
 #include "oc_logger.hpp"
 
@@ -232,6 +233,15 @@ namespace OC
 
         std::weak_ptr<std::recursive_mutex> csdkLock();
 
+        OCStackResult findDirectPairingDevices(unsigned short waittime,
+                                         GetDirectPairedCallback callback);
+
+        OCStackResult getDirectPairedDevices(GetDirectPairedCallback callback);
+
+        OCStackResult doDirectPairing(std::shared_ptr<OCDirectPairing> peer, OCPrm_t pmSel,
+                                         const std::string& pinNumber,
+                                         DirectPairingCallback resultCallback);
+
     private:
         PlatformConfig m_cfg;
 
index 0a949e3..535572c 100644 (file)
@@ -268,6 +268,17 @@ namespace OC
                     ResultCallBack resultCallback);
 
             /**
+             * API to provision DirectPairing to devices.
+             *
+             * @param pconf pointer to PCONF (Pairing Configuration).
+             * @param resultCallback Callback will be called when provisioning request receives
+             *                           a response from first resource server.
+             * @return  ::OC_STACK_OK in case of success and other value otherwise.
+             */
+            OCStackResult provisionDirectPairing(const OicSecPconf_t *pconf,
+                    ResultCallBack resultCallback);
+
+            /**
              * This method is used to get linked devices' IDs.
              *
              * @param uuidList Information about the list of linked devices uuids.
index 5f2071a..be9a117 100644 (file)
@@ -28,7 +28,6 @@
 #ifndef OC_REPRESENTATION_H_
 #define OC_REPRESENTATION_H_
 
-
 #include <string>
 #include <sstream>
 #include <vector>
@@ -99,13 +98,28 @@ namespace OC
             // this fix will work in the meantime.
             OCRepresentation(): m_interfaceType(InterfaceType::None){}
 
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+            OCRepresentation(OCRepresentation&& o)
+            {
+                std::memmove(this, &o, sizeof(o));
+            }
+#else
             OCRepresentation(OCRepresentation&&) = default;
+#endif
 
             OCRepresentation(const OCRepresentation&) = default;
 
             OCRepresentation& operator=(const OCRepresentation&) = default;
 
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+            OCRepresentation& operator=(OCRepresentation&& o)
+            {
+                std::memmove(this, &o, sizeof(o));
+                return *this;
+            }
+#else
             OCRepresentation& operator=(OCRepresentation&&) = default;
+#endif
 
             virtual ~OCRepresentation(){}
 
@@ -131,6 +145,8 @@ namespace OC
 
             const std::vector<std::string>& getResourceTypes() const;
 
+            const std::vector<std::string>& getDataModelVersions() const;
+
             void setResourceTypes(const std::vector<std::string>& resourceTypes);
 
             void addResourceType(const std::string& str);
@@ -141,6 +157,8 @@ namespace OC
 
             void addResourceInterface(const std::string& str);
 
+            void addDataModelVersion(const std::string& str);
+
             bool emptyData() const;
 
             int numberOfAttributes() const;
@@ -160,6 +178,10 @@ namespace OC
                 m_values[str] = std::forward<T>(val);
             }
 
+            const std::map<std::string, AttributeValue>& getValues() const {
+                return m_values;
+            }
+
             /**
              *  Retrieve the attribute value associated with the supplied name
              *
@@ -302,12 +324,38 @@ namespace OC
                     // Enable-if required to prevent conversions to alternate types.  This prevents
                     // ambigious conversions in the case where conversions can include a number of
                     // types, such as the string constructor.
+#if (defined(_MSC_VER) ) || (defined(__GNUC__) && (__GNUC__ <= 5))
+                    template<typename T, typename std::enable_if<
+                     std::is_same<T, int>::value ||
+                     std::is_same<T, double>::value ||
+                     std::is_same<T, bool>::value ||
+                     std::is_same<T, std::string>::value ||
+                     std::is_same<T, OCRepresentation>::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 ||
+                     std::is_same<T, std::vector<double>>::value ||
+                     std::is_same<T, std::vector<std::vector<double>>>::value ||
+                     std::is_same<T, std::vector<std::vector<std::vector<double>>>>::value ||
+                     std::is_same<T, std::vector<bool>>::value ||
+                     std::is_same<T, std::vector<std::vector<bool>>>::value ||
+                     std::is_same<T, std::vector<std::vector<std::vector<bool>>>>::value ||
+                     std::is_same<T, std::vector<std::string>>::value ||
+                     std::is_same<T, std::vector<std::vector<std::string>>>::value ||
+                     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
+                     , int>::type = 0// enable_if
+                    >
+#else
                     template<typename T, typename std::enable_if<
                         is_component<T,
                             remove_first<AttributeValue>::type
                             >::value
                         , int>::type = 0
                     >
+#endif
                     operator T() const
                     {
                         return this->getValue<T>();
@@ -452,6 +500,7 @@ namespace OC
             mutable std::map<std::string, AttributeValue> m_values;
             std::vector<std::string> m_resourceTypes;
             std::vector<std::string> m_interfaces;
+            std::vector<std::string> m_dataModelVersions;
 
             InterfaceType m_interfaceType;
     };
index 3fe3a68..bc0bcdb 100644 (file)
@@ -60,7 +60,15 @@ namespace OC
 
             OCResourceIdentifier(const OCResourceIdentifier&) = default;
 
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+            OCResourceIdentifier(OCResourceIdentifier&& o):
+                m_resourceUri(std::move(o.m_resourceUri)),
+                m_representation(o.m_representation)
+            {
+            }
+#else
             OCResourceIdentifier(OCResourceIdentifier&&) = default;
+#endif
 
             OCResourceIdentifier& operator=(const OCResourceIdentifier&) = delete;
 
@@ -103,8 +111,32 @@ namespace OC
     public:
         typedef std::shared_ptr<OCResource> Ptr;
 
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+        OCResource(OCResource&& o):
+            m_clientWrapper(std::move(o.m_clientWrapper)),
+            m_uri(std::move(o.m_uri)),
+            m_resourceId(std::move(o.m_resourceId)),
+            m_devAddr(std::move(o.m_devAddr)),
+            m_useHostString(o.m_useHostString),
+            m_isObservable(o.m_isObservable),
+            m_isCollection(o.m_isCollection),
+            m_resourceTypes(std::move(o.m_resourceTypes)),
+            m_interfaces(std::move(o.m_interfaces)),
+            m_children(std::move(m_children)),
+            m_observeHandle(std::move(m_observeHandle)),
+            m_headerOptions(std::move(m_headerOptions))
+        {
+        }
+#else
         OCResource(OCResource&&) = default;
-        OCResource& operator=(OCResource&&) = default;
+#endif
+        // Explicitly delete the copy ctor since VS2013 would try to generate one, and
+        // the standard says that defaulting the move ctor should delete the copy ctor.
+        OCResource(const OCResource&) = delete;
+
+        // We cannot support copy/move assigns since OCResourceIdentifier doesn't.
+        OCResource& operator=(OCResource&&) = delete;
+        OCResource& operator=(const OCResource&) = delete;
 
         /**
         * Virtual destructor
index e17e3a6..538a134 100644 (file)
@@ -51,6 +51,7 @@ namespace OC
             m_resourceUri{},
             m_queryParameters{},
             m_requestHandlerFlag{},
+            m_messageID{},
             m_representation{},
             m_observationInfo{},
             m_headerOptions{},
@@ -59,8 +60,36 @@ namespace OC
         {
         }
 
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+        OCResourceRequest(OCResourceRequest&& o):
+            m_requestType(std::move(o.m_requestType)),
+            m_resourceUri(std::move(o.m_resourceUri)),
+            m_queryParameters(std::move(o.m_queryParameters)),
+            m_requestHandlerFlag(o.m_requestHandlerFlag),
+            m_representation(std::move(o.m_representation)),
+            m_observationInfo(std::move(o.m_observationInfo)),
+            m_headerOptions(std::move(o.m_headerOptions)),
+            m_requestHandle(std::move(o.m_requestHandle)),
+            m_resourceHandle(std::move(o.m_resourceHandle))
+        {
+        }
+        OCResourceRequest& operator=(OCResourceRequest&& o)
+        {
+            m_requestType = std::move(o.m_requestType);
+            m_resourceUri = std::move(o.m_resourceUri);
+            m_queryParameters = std::move(o.m_queryParameters);
+            m_requestHandlerFlag = o.m_requestHandlerFlag;
+            m_representation = std::move(o.m_representation);
+            m_observationInfo = std::move(o.m_observationInfo);
+            m_headerOptions = std::move(o.m_headerOptions);
+            m_requestHandle = std::move(o.m_requestHandle);
+            m_resourceHandle = std::move(o.m_resourceHandle);
+        }
+#else
         OCResourceRequest(OCResourceRequest&&) = default;
         OCResourceRequest& operator=(OCResourceRequest&&) = default;
+#endif
+
         /**
         *  Virtual destructor
         */
@@ -154,11 +183,19 @@ namespace OC
             return m_resourceHandle;
         }
 
+        /**
+        * This API retrieves the request message ID
+        *
+        * @return int16_t value of message ID
+        */
+        int16_t getMessageID() const {return m_messageID;}
+
     private:
         std::string m_requestType;
         std::string m_resourceUri;
         QueryParamsMap m_queryParameters;
         int m_requestHandlerFlag;
+        int16_t m_messageID;
         OCRepresentation m_representation;
         ObservationInfo m_observationInfo;
         HeaderOptions m_headerOptions;
@@ -186,6 +223,11 @@ namespace OC
             m_requestHandlerFlag = requestHandlerFlag;
         }
 
+        void setMessageID(int16_t messageID)
+        {
+            m_messageID = messageID;
+        }
+
         void setObservationInfo(const ObservationInfo& observationInfo)
         {
             m_observationInfo = observationInfo;
index 474e90a..b4b8c9f 100644 (file)
@@ -57,8 +57,33 @@ namespace OC
         {
         }
 
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+        OCResourceResponse(OCResourceResponse&& o):
+            m_newResourceUri(std::move(o.m_newResourceUri)),
+            m_errorCode(o.m_errorCode),
+            m_headerOptions(std::move(o.m_headerOptions)),
+            m_interface(std::move(o.m_interface)),
+            m_representation(std::move(o.m_representation)),
+            m_requestHandle(std::move(o.m_requestHandle)),
+            m_resourceHandle(std::move(o.m_resourceHandle)),
+            m_responseResult(std::move(o.m_responseResult))
+        {
+        }
+        OCResourceResponse& operator=(OCResourceResponse&& o)
+        {
+            m_newResourceUri = std::move(o.m_newResourceUri);
+            m_errorCode = o.m_errorCode;
+            m_headerOptions = std::move(o.m_headerOptions);
+            m_interface = std::move(o.m_interface);
+            m_representation = std::move(o.m_representation);
+            m_requestHandle = std::move(o.m_requestHandle);
+            m_resourceHandle = std::move(o.m_resourceHandle);
+            m_responseResult = std::move(o.m_responseResult);
+        }
+#else
         OCResourceResponse(OCResourceResponse&&) = default;
         OCResourceResponse& operator=(OCResourceResponse&&) = default;
+#endif
         virtual ~OCResourceResponse(void) {}
 
         /**
@@ -129,8 +154,8 @@ namespace OC
         *  @param rep reference to the resource's representation
         *  @param interface specifies the interface
         */
-        void setResourceRepresentation(OCRepresentation& rep, std::string interface) {
-            m_interface = interface;
+        void setResourceRepresentation(OCRepresentation& rep, std::string iface) {
+            m_interface = iface;
             m_representation = rep;
         }
 
@@ -139,8 +164,8 @@ namespace OC
         *  @param rep rvalue reference to the resource's representation
         *  @param interface specifies the interface
         */
-        void setResourceRepresentation(OCRepresentation&& rep, std::string interface) {
-            setResourceRepresentation(rep, interface);
+        void setResourceRepresentation(OCRepresentation&& rep, std::string iface) {
+            setResourceRepresentation(rep, iface);
         }
 
         /**
index 1c17c10..85039d0 100644 (file)
@@ -100,7 +100,7 @@ namespace OC
     template<typename T, typename = void>
     struct is_vector
     {
-        constexpr static bool value = false;
+        BOOST_STATIC_CONSTEXPR bool value = false;
     };
 
     template<typename T>
@@ -110,7 +110,7 @@ namespace OC
         >::type
     >
     {
-        constexpr static bool value = true;
+        BOOST_STATIC_CONSTEXPR bool value = true;
     };
 
     // type trait to remove the first type from a parameter-packed list
@@ -132,14 +132,14 @@ namespace OC
     template<typename ToTest, template <typename...> class Base, typename T>
     struct is_component<ToTest, Base<T> >
     {
-        static constexpr bool value = std::is_same<ToTest, T>::value;
+        BOOST_STATIC_CONSTEXPR bool value = std::is_same<ToTest, T>::value;
     };
 
     // Recursive specialization to handle cases with multiple values
     template<typename ToTest, template <typename...> class Base, typename T, typename ...Rest>
     struct is_component<ToTest, Base<T, Rest...> >
     {
-        static constexpr bool value = std::is_same<ToTest, T>::value
+        BOOST_STATIC_CONSTEXPR bool value = std::is_same<ToTest, T>::value
             || is_component<ToTest, Base<Rest...> >::value;
     };
 } // namespace OC
index 2438cb1..3719a63 100644 (file)
@@ -123,6 +123,18 @@ namespace OC
 
         virtual OCStackResult GetDefaultQos(QualityOfService& /*QoS*/)
             {return OC_STACK_NOTIMPL;}
+
+        virtual OCStackResult FindDirectPairingDevices(unsigned short /*waittime*/,
+                       GetDirectPairedCallback& /*callback*/)
+            {return OC_STACK_NOTIMPL;}
+
+        virtual OCStackResult GetDirectPairedDevices(GetDirectPairedCallback& /*callback*/)
+            {return OC_STACK_NOTIMPL;}
+
+        virtual OCStackResult DoDirectPairing(std::shared_ptr<OCDirectPairing> /*peer*/,
+                const OCPrm_t& /*pmSel*/,
+                const std::string& /*pinNumber*/, DirectPairingCallback& /*resultCallback*/)
+            {return OC_STACK_NOTIMPL;}
     };
 }
 
index 33cb27d..e700739 100644 (file)
@@ -75,7 +75,7 @@ namespace OC
             return m_missingInterface;
         }
 
-        virtual const char* what() const noexcept
+        virtual const char* what() const BOOST_NOEXCEPT
         {
             std::string ret;
 
index 4b97938..edcf6f4 100644 (file)
 
 namespace OC
 {
+
+#if defined(_WIN32)
+/** @todo: Remove temporary hacks to solve error C2059: syntax error: 'constant'*/
+#ifdef NO_ERROR
+#undef NO_ERROR
+#endif
+#ifdef DELETE
+#undef DELETE
+#endif
+#endif
+
     namespace InitException
     {
         static const char NO_ERROR[]                   = "No Error";
@@ -107,6 +118,7 @@ namespace OC
         static const char INVALID_ATTRIBUTE[]          = "Invalid Attribute: ";
         static const char INVALID_DEVICE_INFO[]        = "Invalid Device Information";
         static const char UNAUTHORIZED_REQUEST[]       = "Unauthorized Request";
+        static const char TOO_LARGE_REQ[]              = "Request Too Large";
         static const char PDM_DB_NOT_INITIALIZED[]     = "Provisioning DB is not initialized";
         static const char DUPLICATE_UUID[]             = "Duplicate UUID in DB";
         static const char INCONSISTENT_DB[]            = "Data in provisioning DB is inconsistent";
index 16612dd..c659365 100644 (file)
@@ -39,22 +39,31 @@ if target_os == 'android':
        liboc_logger_env.AppendUnique(LIBS = ['gnustl_shared', 'log'])
        liboc_logger_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,liboc_logger.so'])
 
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows']:
        liboc_logger_env.AppendUnique(CFLAGS = ['-Wall', '-std=c99', '-fPIC'])
        liboc_logger_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x', '-fPIC'])
 
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows', 'msys_nt']:
        liboc_logger_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
 
 ######################################################################
 # Source files and Targets
 ######################################################################
-liboc_logger_core = liboc_logger_env.SharedLibrary('oc_logger_core', 'c/oc_logger.c',  OBJPREFIX='core_')
-liboc_logger = liboc_logger_env.SharedLibrary('oc_logger',
+
+oc_logger_libs = []
+
+if target_os in ['windows', 'msys_nt']:
+       # TODO: Add OC_EXPORT API prefixes to enable oc_logger DLL generation.
+       oc_logger_libs += liboc_logger_env.StaticLibrary('oc_logger',
                ['c/oc_logger.c', 'c/oc_console_logger.c', 'cpp/oc_ostream_logger.cpp'])
+else:
+       oc_logger_libs += Flatten(liboc_logger_env.SharedLibrary('oc_logger_core',
+               ['c/oc_logger.c'],  OBJPREFIX='core_'))
+       oc_logger_libs += Flatten(liboc_logger_env.SharedLibrary('oc_logger',
+               ['c/oc_logger.c', 'c/oc_console_logger.c', 'cpp/oc_ostream_logger.cpp']))
 
-liboc_logger_env.InstallTarget([liboc_logger_core, liboc_logger], 'liboc_logger')
-liboc_logger_env.UserInstallTargetLib([liboc_logger_core, liboc_logger], 'liboc_logger')
+liboc_logger_env.InstallTarget(oc_logger_libs, 'oc_logger')
+liboc_logger_env.UserInstallTargetLib(oc_logger_libs, 'oc_logger')
 liboc_logger_env.UserInstallTargetHeader('include/oc_logger.hpp', 'resource', 'oc_logger.hpp')
 liboc_logger_env.UserInstallTargetHeader('include/oc_logger.h', 'resource', 'oc_logger.h')
 liboc_logger_env.UserInstallTargetHeader('include/oc_logger_types.h', 'resource', 'oc_logger_types.h')
index a3a4c91..42a03cb 100644 (file)
@@ -33,14 +33,19 @@ examples_env = lib_env.Clone()
 ######################################################################
 examples_env.PrependUnique(CPPPATH = ['../include'])
 examples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-examples_env.AppendUnique(LIBS = ['oc_logger', 'stdc++'])
+examples_env.AppendUnique(LIBS = ['oc_logger'])
+examples_env.Append(LIBS = ['c_common'])
+
+compiler = env.get('CC')
+if compiler != 'cl':
+       examples_env.AppendUnique(LIBS = ['stdc++'])
 
 target_os = env.get('TARGET_OS')
 if target_os == 'android':
        examples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
        examples_env.AppendUnique(LIBS = ['gnustl_shared'])
 
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows']:
        examples_env.AppendUnique(CFLAGS = Split('-Wall -std=c99 -Werror'))
        examples_env.AppendUnique(CXXFLAGS = Split('-Wall -std=c++0x'))
 
index f2e01ac..e6c8c2c 100644 (file)
@@ -55,9 +55,9 @@ class oc_log_stream : boost::iostreams::sink
  {}
 
  public:
- inline void flush()                                    noexcept { return oc_log_flush(m_log.get()); }
- inline void set_level(const oc_log_level new_level)    noexcept { return oc_log_set_level(m_log.get(), new_level); }
- inline int  set_module(const std::string& module_name) noexcept { return oc_log_set_module(m_log.get(), module_name.c_str()); }
+ inline void flush()                                    BOOST_NOEXCEPT { return oc_log_flush(m_log.get()); }
+ inline void set_level(const oc_log_level new_level)    BOOST_NOEXCEPT { return oc_log_set_level(m_log.get(), new_level); }
+ inline int  set_module(const std::string& module_name) BOOST_NOEXCEPT { return oc_log_set_module(m_log.get(), module_name.c_str()); }
 
  public:
  std::streamsize write(const char_type *s, std::streamsize n)
index 05186c1..a343e79 100644 (file)
@@ -40,7 +40,7 @@ ocprovision_env.AppendUnique(CPPPATH = [
                ])
 
 target_os = env.get('TARGET_OS')
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
        ocprovision_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-fPIC'])
 
 if target_os == 'android':
index ceb52bf..07600fe 100644 (file)
@@ -41,13 +41,14 @@ examples_env.AppendUnique(CPPPATH = [
         '../../oc_logger/include',
         '../../csdk/connectivity/api',
         '../../csdk/security/include',
+        '../../csdk/security/include/internal',
         '../../csdk/security/provisioning/include',
         '../../csdk/security/provisioning/include/oxm',
         '../../csdk/security/provisioning/include/internal'
                ])
 
 target_os = env.get('TARGET_OS')
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
        examples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
 
        # Note: 'pthread' is in libc for android. On other platform, if use
index 781f654..04cb534 100644 (file)
Binary files a/resource/provisioning/examples/oic_svr_db_client.dat and b/resource/provisioning/examples/oic_svr_db_client.dat differ
index fb3c609..930d160 100644 (file)
@@ -8,38 +8,32 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
                         },\r
                         {\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/ad",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.ad"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/amacl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.amacl"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        }                  \r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
+                        }\r
                     ],\r
                     "permission": 2\r
                 }\r
             ]\r
         },\r
         "rowneruuid" : "61646D69-6E44-6576-6963-655575696430"\r
-    },    \r
+    },\r
     "pstat": {\r
         "isop": true,\r
         "cm": 0,\r
@@ -81,7 +75,7 @@
         "sct": 1,\r
         "owned": true,\r
         "deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
-        "dpc": false,\r
+        "x.com.samsung.dpc": false,\r
         "devowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
         "rowneruuid": "61646D69-6E44-6576-6963-655575696430"\r
     }\r
index b2c9825..13ca047 100644 (file)
 #include "OCProvisioningManager.h"
 #include "oxmjustworks.h"
 #include "oxmrandompin.h"
+#include "aclresource.h"
+#include "utlist.h"
 
 #define MAX_URI_LENGTH (64)
 #define MAX_PERMISSION_LENGTH (5)
+#define ACL_RESRC_ARRAY_SIZE (3)
 #define CREATE (1)
 #define READ (2)
 #define UPDATE (4)
 
 #define DISCOVERY_TIMEOUT 5
 
+static const OicSecPrm_t  SUPPORTED_PRMS[1] =
+{
+    PRM_PRE_CONFIGURED,
+};
+
 using namespace OC;
 
 DeviceList_t pUnownedDevList, pOwnedDevList;
 static int transferDevIdx, ask = 1;
+static OicSecPconf_t g_pconf;
 
 static FILE* client_open(const char *UNUSED_PARAM, const char *mode)
 {
@@ -79,8 +88,9 @@ void printMenu()
     std::cout << "   7. Unlink Devices"<<std::endl;
     std::cout << "   8. Remove Device"<<std::endl;
     std::cout << "   9. Get Linked Devices"<<std::endl;
-    std::cout << "   10. Get Device Status"<<std::endl;
-    std::cout << "   11. Exit loop"<<std::endl;
+    std::cout << "  10. Get Device Status"<<std::endl;
+    std::cout << "  11. Provision Direct-Pairing Configuration"<<std::endl;
+    std::cout << "  12. Exit loop"<<std::endl;
 }
 
 void moveTransferredDevice()
@@ -263,19 +273,8 @@ int readDeviceNumber(DeviceList_t &list, int count, int *out)
  */
 static void deleteACL(OicSecAcl_t *acl)
 {
-    if (acl)
-    {
-        /* Clean Resources */
-        for (unsigned int i = 0; i < (acl)->resourcesLen; i++)
-        {
-            OICFree((acl)->resources[i]);
-        }
-        OICFree((acl)->resources);
+    DeleteACLList(acl);
 
-        /* Clean ACL node itself */
-        /* Required only if acl was created in heap */
-        OICFree((acl));
-    }
 }
 
 /**
@@ -362,39 +361,54 @@ static int InputACL(OicSecAcl_t *acl)
     printf("Subject : ");
     ret = scanf("%19ms", &temp_id);
 
+    OicSecAce_t* ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+    if(NULL == ace)
+    {
+        OIC_LOG(ERROR, TAG, "Error while memory allocation");
+        return -1;
+    }
+    LL_APPEND(acl->aces, ace);
+
     if (1 == ret)
     {
         for (int i = 0, j = 0; temp_id[i] != '\0'; i++)
         {
             if (DASH != temp_id[i])
-                acl->subject.id[j++] = temp_id[i];
+                ace->subjectuuid.id[j++] = temp_id[i];
         }
         OICFree(temp_id);
     }
     else
     {
+        deleteACL(acl);
         printf("Error while input\n");
         return -1;
     }
 
     //Set Resource.
+    size_t resourcesLen = 0;
     printf("Num. of Resource : ");
-    ret = scanf("%zu", &acl->resourcesLen);
-    if ((1 != ret) || (acl->resourcesLen <= 0 || acl->resourcesLen > 50))
+    ret = scanf("%zu", &resourcesLen);
+    if ((1 != ret) || (resourcesLen <= 0 || resourcesLen > 50))
     {
+        deleteACL(acl);
         printf("Error while input\n");
         return -1;
     }
     printf("-URI of resource\n");
     printf("ex)/oic/sh/temp/0 (Max_URI_Length: 64 Byte )\n");
-    acl->resources = (char **)OICCalloc(acl->resourcesLen, sizeof(char *));
-    if (NULL == acl->resources)
-    {
-        OIC_LOG(ERROR, TAG, "Error while memory allocation");
-        return -1;
-    }
-    for (size_t i = 0; i < acl->resourcesLen; i++)
+    for(size_t i = 0; i < resourcesLen; i++)
     {
+        OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+        if(NULL == rsrc)
+        {
+            deleteACL(acl);
+            OIC_LOG(ERROR, TAG, "Error while memory allocation");
+            return -1;
+        }
+
+        LL_APPEND(ace->resources, rsrc);
+
         printf("[%zu]Resource : ", i + 1);
         ret = scanf("%64ms", &temp_rsc);
         if (1 != ret)
@@ -403,14 +417,97 @@ static int InputACL(OicSecAcl_t *acl)
             return -1;
         }
 
-        acl->resources[i] = OICStrdup(temp_rsc);
+        rsrc->href = OICStrdup(temp_rsc);
         OICFree(temp_rsc);
-        if (NULL == acl->resources[i])
+
+        char* rsrc_in = NULL;
+        int arrLen = 0;
+        while(1)
         {
-            OIC_LOG(ERROR, TAG, "Error while memory allocation");
-            return -1;
+            printf("         Enter Number of resource type for [%s]: ", rsrc_in);
+            for(int ret=0; 1!=ret; )
+            {
+                ret = scanf("%d", &arrLen);
+                for( ; 0x20<=getchar(); );  // for removing overflow garbages
+                                            // '0x20<=code' is character region
+            }
+            if(0 < arrLen && ACL_RESRC_ARRAY_SIZE >= arrLen)
+            {
+                break;
+            }
+            printf("     Entered Wrong Number. Please Enter under %d Again\n", ACL_RESRC_ARRAY_SIZE);
+        }
+
+        rsrc->typeLen = arrLen;
+        rsrc->types = (char**)OICCalloc(arrLen, sizeof(char*));
+        if(!rsrc->types)
+        {
+            OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+            goto error;
+        }
+
+        for(int i = 0; i < arrLen; i++)
+        {
+            printf("         Enter ResourceType[%d] Name: ", i+1);
+            for(int ret=0; 1!=ret; )
+            {
+                ret = scanf("%64ms", &rsrc_in);  // '128' is ACL_RESRC_MAX_LEN
+                for( ; 0x20<=getchar(); );  // for removing overflow garbages
+                                            // '0x20<=code' is character region
+            }
+            rsrc->types[i] = OICStrdup(rsrc_in);
+            OICFree(rsrc_in);
+            if(!rsrc->types[i])
+            {
+                OIC_LOG(ERROR, TAG, "createAcl: OICStrdup error return");
+                goto error;
+            }
+        }
+
+        while(1)
+        {
+            printf("         Enter Number of interface name for [%s]: ", rsrc_in);
+            for(int ret=0; 1!=ret; )
+            {
+                ret = scanf("%d", &arrLen);
+                for( ; 0x20<=getchar(); );  // for removing overflow garbages
+                                            // '0x20<=code' is character region
+            }
+            if(0 < arrLen && ACL_RESRC_ARRAY_SIZE >= arrLen)
+            {
+                break;
+            }
+            printf("     Entered Wrong Number. Please Enter under %d Again\n", ACL_RESRC_ARRAY_SIZE);
+        }
+
+        rsrc->interfaceLen = arrLen;
+        rsrc->interfaces = (char**)OICCalloc(arrLen, sizeof(char*));
+        if(!rsrc->interfaces)
+        {
+            OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+            goto error;
+        }
+
+        for(int i = 0; i < arrLen; i++)
+        {
+            printf("         Enter ResourceType[%d] Name: ", i+1);
+            for(int ret=0; 1!=ret; )
+            {
+                ret = scanf("%64ms", &rsrc_in);  // '128' is ACL_RESRC_MAX_LEN
+                for( ; 0x20<=getchar(); );  // for removing overflow garbages
+                                            // '0x20<=code' is character region
+            }
+            rsrc->interfaces[i] = OICStrdup(rsrc_in);
+            OICFree(rsrc_in);
+            if(!rsrc->interfaces[i])
+            {
+                OIC_LOG(ERROR, TAG, "createAcl: OICStrdup error return");
+                goto error;
+            }
         }
+
     }
+
     // Set Permission
     do
     {
@@ -421,9 +518,9 @@ static int InputACL(OicSecAcl_t *acl)
         if (1 != ret)
         {
             printf("Error while input\n");
-            return -1;
+            goto error;
         }
-        ret = CalculateAclPermission(temp_pms, &(acl->permission));
+        ret = CalculateAclPermission(temp_pms, &(ace->permission));
         OICFree(temp_pms);
     } while (0 != ret );
 
@@ -436,7 +533,7 @@ static int InputACL(OicSecAcl_t *acl)
     if (1 != ret)
     {
         printf("Error while input\n");
-        return -1;
+        goto error;
     }
 
     for (int k = 0, j = 0; temp_id[k] != '\0'; k++)
@@ -449,6 +546,10 @@ static int InputACL(OicSecAcl_t *acl)
     OICFree(temp_id);
 
     return 0;
+
+error:
+    DeleteACLList(acl);
+    return -1;
 }
 
 static int InputCredentials(Credential &cred)
@@ -504,6 +605,196 @@ static int InputCredentials(Credential &cred)
    return 0;
 }
 
+static void deletePconf()
+{
+    OICFree(g_pconf.prm);
+    //free pdacl
+    OicSecPdAcl_t* acl = g_pconf.pdacls;
+    if (acl)
+    {
+        /* Clean Resources */
+        for (unsigned int i = 0; i < (acl)->resourcesLen; i++)
+        {
+            OICFree((acl)->resources[i]);
+        }
+        OICFree((acl)->resources);
+
+        /* Clean ACL node itself */
+        /* Required only if acl was created in heap */
+        OICFree((acl));
+    }
+    memset(&g_pconf, 0, sizeof(OicSecPconf_t));
+}
+
+static OicSecPdAcl_t* InputPdACL()
+{
+    int ret;
+    char *temp_rsc, *temp_pms;
+
+    printf("******************************************************************************\n");
+    printf("-Set ACL policy for target DP device\n");
+    printf("******************************************************************************\n");
+
+    OicSecPdAcl_t *acl = (OicSecPdAcl_t *)OICCalloc(1,sizeof(OicSecPdAcl_t));
+    if (NULL == acl)
+    {
+        OIC_LOG(ERROR, TAG, "Error while memory allocation");
+        return NULL;
+    }
+
+    //Set Resource.
+    printf("Num. of Resource : ");
+    ret = scanf("%zu", &acl->resourcesLen);
+    if ((1 != ret) || (acl->resourcesLen <= 0 || acl->resourcesLen > 50))
+    {
+        printf("Error while input\n");
+        OICFree(acl);
+        return NULL;
+    }
+    printf("-URI of resource\n");
+    printf("ex)/oic/sh/temp/0 (Max_URI_Length: 64 Byte )\n");
+    acl->resources = (char **)OICCalloc(acl->resourcesLen, sizeof(char *));
+    if (NULL == acl->resources)
+    {
+        OIC_LOG(ERROR, TAG, "Error while memory allocation");
+        OICFree(acl);
+        return NULL;
+    }
+    for (size_t i = 0; i < acl->resourcesLen; i++)
+    {
+        printf("[%zu]Resource : ", i + 1);
+        ret = scanf("%64ms", &temp_rsc);
+        if (1 != ret)
+        {
+            printf("Error while input\n");
+            OICFree(acl->resources);
+            OICFree(acl);
+            return NULL;
+        }
+
+        acl->resources[i] = OICStrdup(temp_rsc);
+        OICFree(temp_rsc);
+        if (NULL == acl->resources[i])
+        {
+            OIC_LOG(ERROR, TAG, "Error while memory allocation");
+            OICFree(acl->resources);
+            OICFree(acl);
+            return NULL;
+        }
+    }
+
+    // Set Permission
+    do
+    {
+        printf("-Set the permission(C,R,U,D,N)\n");
+        printf("ex) CRUDN, CRU_N,..(5 Charaters)\n");
+        printf("Permission : ");
+        ret = scanf("%5ms", &temp_pms);
+        if (1 != ret)
+        {
+            printf("Error while input\n");
+            OICFree(acl->resources);
+            OICFree(acl);
+            return NULL;
+        }
+        ret = CalculateAclPermission(temp_pms, &(acl->permission));
+        OICFree(temp_pms);
+    } while (0 != ret );
+
+    return acl;
+}
+
+void provisionDirectPairingCB(PMResultList_t *result, int hasError)
+{
+    if (hasError)
+    {
+        std::cout << "Error in provisioning operation!"<<std::endl;
+    }
+    else
+    {
+        std::cout<< "\nReceived provisioning results: Direct Pairing is successful ";
+        for (unsigned int i = 0; i < result->size(); i++)
+        {
+            std::cout << "Result is = " << result->at(i).res <<" for device ";
+            printUuid(result->at(i).deviceId);
+        }
+
+        delete result;
+    }
+    deletePconf();
+    printMenu();
+    ask = 1;
+}
+
+static void provisionDP(int dev_num)
+{
+    OCStackResult rst;
+    std::string pin("");
+
+    // set enable dp
+    g_pconf.edp = true;
+
+    // set default supported PRM types
+    g_pconf.prmLen = sizeof(SUPPORTED_PRMS)/sizeof(OicSecPrm_t);
+    g_pconf.prm = (OicSecPrm_t *)OICCalloc(g_pconf.prmLen, sizeof(OicSecPrm_t));
+    if(g_pconf.prm)
+    {
+        for (size_t i=0; i < g_pconf.prmLen; i++)
+        {
+            g_pconf.prm[i] = SUPPORTED_PRMS[i];
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "create prm error return");
+        goto PVDP_ERROR;
+    }
+
+    std::cout << "Enter PIN to be configured: ";
+    while (1)
+    {
+        std::cin >> pin;
+        if (pin.length() == DP_PIN_LENGTH)
+        {
+            break;
+        }
+        else
+        {
+            std::cout << "PIN length should be 8, Enter again: ";
+        }
+    }
+
+    memcpy(g_pconf.pin.val, pin.c_str(), DP_PIN_LENGTH);
+
+    // set default pdacl
+
+    g_pconf.pdacls = InputPdACL();
+    if(!g_pconf.pdacls)
+    {
+        OIC_LOG(ERROR, TAG, "InputPdACL error return");
+        goto PVDP_ERROR;
+    }
+
+    // call |OCProvisionDirectPairing| API actually
+    // calling this API with callback actually acts like blocking
+    // for error checking, the return value saved and printed
+    rst = pOwnedDevList[dev_num-1]->provisionDirectPairing(&g_pconf, provisionDirectPairingCB);
+    if(OC_STACK_OK != rst)
+    {
+        OIC_LOG_V(ERROR, TAG, "OCProvisionDirectPairing API error: %d", rst);
+        if (OC_STACK_UNAUTHORIZED_REQ == rst)
+        {
+            OIC_LOG(ERROR, TAG, "Target Server NOT Support Direct-Pairing !!! (DPC == false)");
+        }
+        goto PVDP_ERROR;
+    }
+    return;
+
+PVDP_ERROR:
+    deletePconf();  // after here |acl| points nothing
+    ask = 1;
+}
+
 int main(void)
 {
     OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
@@ -890,6 +1181,36 @@ int main(void)
                     }
 
                 case 11:
+                    {
+                        unsigned int devNum;
+
+                        if (!pOwnedDevList.size())
+                        {
+                            std::cout <<"There are no Owned devices yet,"
+                                " may need to discover"<<std::endl;
+                            break;
+                        }
+
+                        for (unsigned int i = 0; i < pOwnedDevList.size(); i++ )
+                        {
+                            std::cout << i+1 << ": "<< pOwnedDevList[i]->getDeviceID() <<" From IP:";
+                            std::cout << pOwnedDevList[i]->getDevAddr() <<std::endl;
+                        }
+
+                        std::cout <<"Select device number: "<<std::endl;
+                        std::cin >> devNum;
+                        if (devNum > pOwnedDevList.size())
+                        {
+                            std::cout <<"Invalid device number"<<std::endl;
+                            break;
+                        }
+
+                        ask = 0;
+                        provisionDP(devNum);
+
+                        break;
+                    }
+                case 12:
                 default:
                     out = 1;
                     break;
index 8a2c076..17ebd68 100644 (file)
@@ -30,7 +30,7 @@ namespace OC
         OCStackResult result;
         auto cLock = OCPlatform_impl::Instance().csdkLock().lock();
 
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             result = OCInitPM(dbPath.c_str());
@@ -52,7 +52,7 @@ namespace OC
         auto csdkLock = OCPlatform_impl::Instance().csdkLock();
         auto cLock = csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             result = OCDiscoverUnownedDevices(timeout, &pDevList);
@@ -91,7 +91,7 @@ namespace OC
         auto csdkLock = OCPlatform_impl::Instance().csdkLock();
         auto cLock = csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             result = OCDiscoverOwnedDevices(timeout, &pDevList);
@@ -124,13 +124,13 @@ namespace OC
     OCStackResult OCSecure::setOwnerTransferCallbackData(OicSecOxm_t oxm,
             OTMCallbackData_t* callbackData, InputPinCallback inputPin)
     {
-        if(NULL == callbackData || oxm >= OIC_OXM_COUNT)
+        if (NULL == callbackData || oxm >= OIC_OXM_COUNT)
         {
             oclog() <<"Invalid callbackData or OXM type";
             return OC_STACK_INVALID_PARAM;
         }
 
-        if((OIC_RANDOM_DEVICE_PIN == oxm) && !inputPin)
+        if ((OIC_RANDOM_DEVICE_PIN == oxm) && !inputPin)
         {
             oclog() <<"for OXM type DEVICE_PIN, inputPin callback can't be null";
             return OC_STACK_INVALID_PARAM;
@@ -139,11 +139,11 @@ namespace OC
         OCStackResult result;
         auto cLock = OCPlatform_impl::Instance().csdkLock().lock();
 
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             result = OCSetOwnerTransferCallbackData(oxm, callbackData);
-            if(result == OC_STACK_OK && (OIC_RANDOM_DEVICE_PIN == oxm))
+            if (result == OC_STACK_OK && (OIC_RANDOM_DEVICE_PIN == oxm))
             {
                 SetInputPinCB(inputPin);
             }
@@ -167,7 +167,7 @@ namespace OC
         auto csdkLock = OCPlatform_impl::Instance().csdkLock();
         auto cLock = csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
 
@@ -207,7 +207,7 @@ namespace OC
 
     OCStackResult OCSecure::setDisplayPinCB(GeneratePinCallback displayPin)
     {
-        if(!displayPin)
+        if (!displayPin)
         {
             oclog() <<"displayPin can't be null";
             return OC_STACK_INVALID_PARAM;
@@ -216,7 +216,7 @@ namespace OC
         OCStackResult result = OC_STACK_OK;
         auto cLock = OCPlatform_impl::Instance().csdkLock().lock();
 
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             SetGeneratePinCB(displayPin);
@@ -269,7 +269,7 @@ namespace OC
 
     OCSecureResource::~OCSecureResource()
     {
-        if(devPtr)
+        if (devPtr)
         {
             OCDeleteDiscoveredDevices(devPtr);
         }
@@ -277,7 +277,7 @@ namespace OC
 
     OCStackResult OCSecureResource::doOwnershipTransfer(ResultCallBack resultCallback)
     {
-        if(!resultCallback)
+        if (!resultCallback)
         {
             oclog() <<"Result callback can't be null";
             return OC_STACK_INVALID_CALLBACK;
@@ -286,7 +286,7 @@ namespace OC
         OCStackResult result;
         auto cLock = m_csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             ProvisionContext* context = new ProvisionContext(resultCallback);
 
@@ -305,12 +305,12 @@ namespace OC
     OCStackResult OCSecureResource::provisionACL( const OicSecAcl_t* acl,
             ResultCallBack resultCallback)
     {
-        if(!acl)
+        if (!acl)
         {
             oclog() <<"ACL can't be null";
             return OC_STACK_INVALID_PARAM;
         }
-        if(!resultCallback)
+        if (!resultCallback)
         {
             oclog() <<"result callback can not be null";
             return OC_STACK_INVALID_CALLBACK;
@@ -319,7 +319,7 @@ namespace OC
         OCStackResult result;
         auto cLock = m_csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             ProvisionContext* context = new ProvisionContext(resultCallback);
 
@@ -339,7 +339,7 @@ namespace OC
     OCStackResult OCSecureResource::provisionCredentials(const Credential &cred,
             const OCSecureResource &device2, ResultCallBack resultCallback)
     {
-        if(!resultCallback)
+        if (!resultCallback)
         {
             oclog() << "Result calback can't be null";
             return OC_STACK_INVALID_CALLBACK;
@@ -348,7 +348,7 @@ namespace OC
         OCStackResult result;
         auto cLock = m_csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             ProvisionContext* context = new ProvisionContext(resultCallback);
 
@@ -371,7 +371,7 @@ namespace OC
             const OicSecAcl_t* acl1, const OCSecureResource &device2, const OicSecAcl_t* acl2,
             ResultCallBack resultCallback)
     {
-        if(!resultCallback)
+        if (!resultCallback)
         {
             oclog() << "Result callback can not be null";
             return OC_STACK_INVALID_CALLBACK;
@@ -380,7 +380,7 @@ namespace OC
         OCStackResult result;
         auto cLock = m_csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             ProvisionContext* context = new ProvisionContext(resultCallback);
 
@@ -403,7 +403,7 @@ namespace OC
     OCStackResult OCSecureResource::unlinkDevices(const OCSecureResource &device2,
             ResultCallBack resultCallback)
     {
-        if(!resultCallback)
+        if (!resultCallback)
         {
             oclog() << "Result calback can't be null";
             return OC_STACK_INVALID_CALLBACK;
@@ -412,7 +412,7 @@ namespace OC
         OCStackResult result;
         auto cLock = m_csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             ProvisionContext* context = new ProvisionContext(resultCallback);
 
@@ -432,7 +432,7 @@ namespace OC
     OCStackResult OCSecureResource::removeDevice(unsigned short waitTimeForOwnedDeviceDiscovery,
             ResultCallBack resultCallback)
     {
-        if(!resultCallback)
+        if (!resultCallback)
         {
             oclog() << "Result calback can't be null";
             return OC_STACK_INVALID_CALLBACK;
@@ -441,7 +441,7 @@ namespace OC
         OCStackResult result;
         auto cLock = m_csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             ProvisionContext* context = new ProvisionContext(resultCallback);
 
@@ -465,7 +465,7 @@ namespace OC
         auto devUuid = devPtr->doxm->deviceID;
         auto cLock = m_csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
 
@@ -488,6 +488,40 @@ namespace OC
         return result;
     }
 
+    OCStackResult OCSecureResource::provisionDirectPairing( const OicSecPconf_t* pconf,
+            ResultCallBack resultCallback)
+    {
+        if (!pconf)
+        {
+            oclog() <<"PCONF can't be null";
+            return OC_STACK_INVALID_PARAM;
+        }
+        if (!resultCallback)
+        {
+            oclog() <<"result callback can not be null";
+            return OC_STACK_INVALID_CALLBACK;
+        }
+
+        OCStackResult result;
+        auto cLock = m_csdkLock.lock();
+
+        if (cLock)
+        {
+            ProvisionContext* context = new ProvisionContext(resultCallback);
+
+            std::lock_guard<std::recursive_mutex> lock(*cLock);
+            result = OCProvisionDirectPairing(static_cast<void*>(context),
+                    devPtr, const_cast<OicSecPconf_t*>(pconf),
+                    &OCSecureResource::callbackWrapper);
+        }
+        else
+        {
+            oclog() <<"Mutex not found";
+            result = OC_STACK_ERROR;
+        }
+        return result;
+    }
+
     std::string OCSecureResource::getDeviceID()
     {
         std::ostringstream deviceId("");
@@ -498,6 +532,7 @@ namespace OC
         if (OC_STACK_OK == ConvertUuidToStr(&(devPtr->doxm->deviceID), &devID))
         {
             deviceId << devID;
+            free(devID);
         }
         else
         {
index 38e27bf..9e44e06 100644 (file)
@@ -173,4 +173,23 @@ namespace OCProvisioningTest
         OICFree(acl2);
     }
 
+    TEST(ProvisionDirectPairingTest, ProvisionDirectPairingTestNullPconf)
+    {
+        OCSecureResource device;
+        EXPECT_EQ(OC_STACK_INVALID_PARAM, device.provisionDirectPairing(nullptr, resultCallback));
+    }
+
+    TEST(ProvisionDirectPairingTest, ProvisionDirectPairingTestNullCallback)
+    {
+        OCSecureResource device;
+        OicSecPconf_t *pconf = (OicSecPconf_t *)OICCalloc(1,sizeof(OicSecPconf_t));
+        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionDirectPairing(pconf, nullptr));
+        OICFree(pconf);
+    }
+
+    TEST(ProvisionDirectPairingTest, ProvisionDirectPairingTestNullCallbackNUllPconf)
+    {
+        OCSecureResource device;
+        EXPECT_EQ(OC_STACK_INVALID_PARAM, device.provisionDirectPairing(nullptr, nullptr));
+    }
 }
index cafcfa9..59cba9a 100644 (file)
@@ -33,8 +33,25 @@ using namespace OC;
 
 namespace
 {
-        CAManager::AdapterChangedCallback g_adapterHandler = NULL;
-        CAManager::ConnectionChangedCallback g_connectionHandler = NULL;
+        CAManager::AdapterChangedCallback g_adapterHandler = nullptr;
+        CAManager::ConnectionChangedCallback g_connectionHandler = nullptr;
+}
+
+OCStackResult convertCAResultToOCResult(CAResult_t caResult)
+{
+    switch (caResult)
+    {
+        case CA_STATUS_OK:
+            return OC_STACK_OK;
+        case CA_STATUS_INVALID_PARAM:
+            return OC_STACK_INVALID_PARAM;
+        case CA_STATUS_FAILED:
+            return OC_STACK_ERROR;
+        case CA_NOT_SUPPORTED:
+            return OC_STACK_NOTIMPL;
+        default:
+            return OC_STACK_ERROR;
+    }
 }
 
 void DefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
@@ -63,13 +80,19 @@ OCStackResult CAManager::setNetworkMonitorHandler(AdapterChangedCallback adapter
     CAResult_t ret = CARegisterNetworkMonitorHandler(DefaultAdapterStateChangedHandler,
                                                      DefaultConnectionStateChangedHandler);
 
-    switch (ret)
-    {
-        case CA_STATUS_OK:
-            return OC_STACK_OK;
-        case CA_NOT_SUPPORTED:
-            return OC_STACK_NOTIMPL;
-        default:
-            return OC_STACK_ERROR;
-    }
+    return convertCAResultToOCResult(ret);
+}
+
+OCStackResult CAManager::setPortNumberToAssign(OCTransportAdapter adapter,
+                                               OCTransportFlags flag, uint16_t port)
+{
+    CAResult_t ret = CASetPortNumberToAssign((CATransportAdapter_t) adapter,
+                                             (CATransportFlags_t) flag, port);
+
+    return convertCAResultToOCResult(ret);
+}
+
+uint16_t CAManager::getAssignedPortNumber(OCTransportAdapter adapter, OCTransportFlags flag)
+{
+    return CAGetAssignedPortNumber((CATransportAdapter_t) adapter, (CATransportFlags_t) flag);
 }
index 23752b9..958d44d 100644 (file)
@@ -37,7 +37,7 @@ namespace OC
         // if the config type is server, we ought to never get called.  If the config type
         // is both, we count on the server to run the thread and do the initialize
 
-        if(m_cfg.mode == ModeType::Client)
+        if (m_cfg.mode == ModeType::Client)
         {
             OCTransportFlags serverFlags =
                             static_cast<OCTransportFlags>(m_cfg.serverConnectivity & CT_MASK_FLAGS);
@@ -45,7 +45,7 @@ namespace OC
                             static_cast<OCTransportFlags>(m_cfg.clientConnectivity & CT_MASK_FLAGS);
             OCStackResult result = OCInit1(OC_CLIENT, serverFlags, clientFlags);
 
-            if(OC_STACK_OK != result)
+            if (OC_STACK_OK != result)
             {
                 throw InitializeException(OC::InitException::STACK_INIT_ERROR, result);
             }
@@ -57,7 +57,7 @@ namespace OC
 
     InProcClientWrapper::~InProcClientWrapper()
     {
-        if(m_threadRun && m_listeningThread.joinable())
+        if (m_threadRun && m_listeningThread.joinable())
         {
             m_threadRun = false;
             m_listeningThread.join();
@@ -65,7 +65,7 @@ namespace OC
 
         // only stop if we are the ones who actually called 'init'.  We are counting
         // on the server to do the stop.
-        if(m_cfg.mode == ModeType::Client)
+        if (m_cfg.mode == ModeType::Client)
         {
             OCStop();
         }
@@ -77,7 +77,7 @@ namespace OC
         {
             OCStackResult result;
             auto cLock = m_csdkLock.lock();
-            if(cLock)
+            if (cLock)
             {
                 std::lock_guard<std::recursive_mutex> lock(*cLock);
                 result = OCProcess();
@@ -87,7 +87,7 @@ namespace OC
                 result = OC_STACK_ERROR;
             }
 
-            if(result != OC_STACK_OK)
+            if (result != OC_STACK_OK)
             {
                 // TODO: do something with result if failed?
             }
@@ -99,7 +99,7 @@ namespace OC
 
     OCRepresentation parseGetSetCallback(OCClientResponse* clientResponse)
     {
-        if(clientResponse->payload == nullptr ||
+        if (clientResponse->payload == nullptr ||
                 (
                     clientResponse->payload->type != PAYLOAD_TYPE_DEVICE &&
                     clientResponse->payload->type != PAYLOAD_TYPE_PLATFORM &&
@@ -116,7 +116,7 @@ namespace OC
         //OCPayloadDestroy(clientResponse->payload);
 
         std::vector<OCRepresentation>::const_iterator it = oc.representations().begin();
-        if(it == oc.representations().end())
+        if (it == oc.representations().end())
         {
             return OCRepresentation();
         }
@@ -140,7 +140,7 @@ namespace OC
         ClientCallbackContext::ListenContext* context =
             static_cast<ClientCallbackContext::ListenContext*>(ctx);
 
-        if(clientResponse->result != OC_STACK_OK)
+        if (clientResponse->result != OC_STACK_OK)
         {
             oclog() << "listenCallback(): failed to create resource. clientResponse: "
                     << clientResponse->result
@@ -149,7 +149,7 @@ namespace OC
             return OC_STACK_KEEP_TRANSACTION;
         }
 
-        if(!clientResponse->payload || clientResponse->payload->type != PAYLOAD_TYPE_DISCOVERY)
+        if (!clientResponse->payload || clientResponse->payload->type != PAYLOAD_TYPE_DISCOVERY)
         {
             oclog() << "listenCallback(): clientResponse payload was null or the wrong type"
                 << std::flush;
@@ -158,7 +158,7 @@ namespace OC
 
         auto clientWrapper = context->clientWrapper.lock();
 
-        if(!clientWrapper)
+        if (!clientWrapper)
         {
             oclog() << "listenCallback(): failed to get a shared_ptr to the client wrapper"
                     << std::flush;
@@ -241,7 +241,7 @@ namespace OC
             OCConnectivityType connectivityType,
             FindCallback& callback, QualityOfService QoS)
     {
-        if(!callback)
+        if (!callback)
         {
             return OC_STACK_INVALID_PARAM;
         }
@@ -252,14 +252,13 @@ namespace OC
 
         ClientCallbackContext::ListenContext* context =
             new ClientCallbackContext::ListenContext(callback, shared_from_this());
-        OCCallbackData cbdata(
-                static_cast<void*>(context),
-                listenCallback,
-                [](void* c){delete static_cast<ClientCallbackContext::ListenContext*>(c);}
-            );
+        OCCallbackData cbdata;
+        cbdata.context = static_cast<void*>(context),
+        cbdata.cb      = listenCallback;
+        cbdata.cd      = [](void* c){delete (ClientCallbackContext::ListenContext*)c;};
 
         auto cLock = m_csdkLock.lock();
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             result = OCDoResource(nullptr, OC_REST_DISCOVER,
@@ -355,7 +354,7 @@ namespace OC
             FindDeviceCallback& callback,
             QualityOfService QoS)
     {
-        if(!callback)
+        if (!callback)
         {
             return OC_STACK_INVALID_PARAM;
         }
@@ -365,14 +364,14 @@ namespace OC
 
         ClientCallbackContext::DeviceListenContext* context =
             new ClientCallbackContext::DeviceListenContext(callback, shared_from_this());
-        OCCallbackData cbdata(
-                static_cast<void*>(context),
-                listenDeviceCallback,
-                [](void* c){delete static_cast<ClientCallbackContext::DeviceListenContext*>(c);}
-                );
+        OCCallbackData cbdata;
+
+        cbdata.context = static_cast<void*>(context),
+        cbdata.cb      = listenDeviceCallback;
+        cbdata.cd      = [](void* c){delete (ClientCallbackContext::DeviceListenContext*)c;};
 
         auto cLock = m_csdkLock.lock();
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             result = OCDoResource(nullptr, OC_REST_DISCOVER,
@@ -393,7 +392,7 @@ namespace OC
     void parseServerHeaderOptions(OCClientResponse* clientResponse,
                     HeaderOptions& serverHeaderOptions)
     {
-        if(clientResponse)
+        if (clientResponse)
         {
             // Parse header options from server
             uint16_t optionID;
@@ -426,7 +425,7 @@ namespace OC
         OCRepresentation rep;
         HeaderOptions serverHeaderOptions;
         OCStackResult result = clientResponse->result;
-        if(result == OC_STACK_OK)
+        if (result == OC_STACK_OK)
         {
             parseServerHeaderOptions(clientResponse, serverHeaderOptions);
             try
@@ -450,24 +449,24 @@ namespace OC
         const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
         GetCallback& callback, QualityOfService QoS)
     {
-        if(!callback)
+        if (!callback)
         {
             return OC_STACK_INVALID_PARAM;
         }
         OCStackResult result;
         ClientCallbackContext::GetContext* ctx =
             new ClientCallbackContext::GetContext(callback);
-        OCCallbackData cbdata(
-                static_cast<void*>(ctx),
-                getResourceCallback,
-                [](void* c){delete static_cast<ClientCallbackContext::GetContext*>(c);}
-                );
+        OCCallbackData cbdata;
+        cbdata.context = static_cast<void*>(ctx),
+        cbdata.cb      = getResourceCallback;
+        cbdata.cd      = [](void* c){delete (ClientCallbackContext::GetContext*)c;};
+
 
         std::string uri = assembleSetResourceUri(resourceUri, queryParams);
 
         auto cLock = m_csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             OCHeaderOption options[MAX_HEADER_OPTIONS];
@@ -524,24 +523,33 @@ namespace OC
     std::string InProcClientWrapper::assembleSetResourceUri(std::string uri,
         const QueryParamsMap& queryParams)
     {
-        if(uri.back() == '/')
+        if (!uri.empty())
         {
-            uri.resize(uri.size()-1);
+            if (uri.back() == '/')
+            {
+                uri.resize(uri.size() - 1);
+            }
         }
 
         ostringstream paramsList;
-        if(queryParams.size() > 0)
+        if (queryParams.size() > 0)
         {
             paramsList << '?';
         }
 
-        for(auto& param : queryParams)
+        for (auto& param : queryParams)
         {
             paramsList << param.first <<'='<<param.second<<';';
         }
 
         std::string queryString = paramsList.str();
-        if(queryString.back() == ';')
+
+        if (queryString.empty())
+        {
+            return uri;
+        }
+
+        if (queryString.back() == ';')
         {
             queryString.resize(queryString.size() - 1);
         }
@@ -569,23 +577,23 @@ namespace OC
         const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
         PostCallback& callback, QualityOfService QoS)
     {
-        if(!callback)
+        if (!callback)
         {
             return OC_STACK_INVALID_PARAM;
         }
         OCStackResult result;
         ClientCallbackContext::SetContext* ctx = new ClientCallbackContext::SetContext(callback);
-        OCCallbackData cbdata(
-                static_cast<void*>(ctx),
-                setResourceCallback,
-                [](void* c){delete static_cast<ClientCallbackContext::SetContext*>(c);}
-                );
+        OCCallbackData cbdata;
+        cbdata.context = static_cast<void*>(ctx),
+        cbdata.cb      = setResourceCallback;
+        cbdata.cd      = [](void* c){delete (ClientCallbackContext::SetContext*)c;};
+
 
         std::string url = assembleSetResourceUri(uri, queryParams);
 
         auto cLock = m_csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             OCHeaderOption options[MAX_HEADER_OPTIONS];
@@ -615,23 +623,23 @@ namespace OC
         const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
         PutCallback& callback, QualityOfService QoS)
     {
-        if(!callback)
+        if (!callback)
         {
             return OC_STACK_INVALID_PARAM;
         }
         OCStackResult result;
         ClientCallbackContext::SetContext* ctx = new ClientCallbackContext::SetContext(callback);
-        OCCallbackData cbdata(
-                static_cast<void*>(ctx),
-                setResourceCallback,
-                [](void* c){delete static_cast<ClientCallbackContext::SetContext*>(c);}
-                );
+        OCCallbackData cbdata;
+        cbdata.context = static_cast<void*>(ctx),
+        cbdata.cb      = setResourceCallback;
+        cbdata.cd      = [](void* c){delete (ClientCallbackContext::SetContext*)c;};
+
 
         std::string url = assembleSetResourceUri(uri, queryParams).c_str();
 
         auto cLock = m_csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             OCDoHandle handle;
@@ -663,7 +671,7 @@ namespace OC
             static_cast<ClientCallbackContext::DeleteContext*>(ctx);
         HeaderOptions serverHeaderOptions;
 
-        if(clientResponse->result == OC_STACK_OK)
+        if (clientResponse->result == OC_STACK_OK)
         {
             parseServerHeaderOptions(clientResponse, serverHeaderOptions);
         }
@@ -679,22 +687,22 @@ namespace OC
         DeleteCallback& callback,
         QualityOfService /*QoS*/)
     {
-        if(!callback)
+        if (!callback)
         {
             return OC_STACK_INVALID_PARAM;
         }
         OCStackResult result;
         ClientCallbackContext::DeleteContext* ctx =
             new ClientCallbackContext::DeleteContext(callback);
-        OCCallbackData cbdata(
-                static_cast<void*>(ctx),
-                deleteResourceCallback,
-                [](void* c){delete static_cast<ClientCallbackContext::DeleteContext*>(c);}
-                );
+        OCCallbackData cbdata;
+        cbdata.context = static_cast<void*>(ctx),
+        cbdata.cb      = deleteResourceCallback;
+        cbdata.cd      = [](void* c){delete (ClientCallbackContext::DeleteContext*)c;};
+
 
         auto cLock = m_csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             OCHeaderOption options[MAX_HEADER_OPTIONS];
 
@@ -728,7 +736,7 @@ namespace OC
         HeaderOptions serverHeaderOptions;
         uint32_t sequenceNumber = clientResponse->sequenceNumber;
         OCStackResult result = clientResponse->result;
-        if(clientResponse->result == OC_STACK_OK)
+        if (clientResponse->result == OC_STACK_OK)
         {
             parseServerHeaderOptions(clientResponse, serverHeaderOptions);
             try
@@ -743,7 +751,7 @@ namespace OC
         std::thread exec(context->callback, serverHeaderOptions, attrs,
                     result, sequenceNumber);
         exec.detach();
-        if(sequenceNumber == OC_OBSERVE_DEREGISTER)
+        if (sequenceNumber == OC_OBSERVE_DEREGISTER)
         {
             return OC_STACK_DELETE_TRANSACTION;
         }
@@ -756,7 +764,7 @@ namespace OC
         const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
         ObserveCallback& callback, QualityOfService QoS)
     {
-        if(!callback)
+        if (!callback)
         {
             return OC_STACK_INVALID_PARAM;
         }
@@ -764,11 +772,11 @@ namespace OC
 
         ClientCallbackContext::ObserveContext* ctx =
             new ClientCallbackContext::ObserveContext(callback);
-        OCCallbackData cbdata(
-                static_cast<void*>(ctx),
-                observeResourceCallback,
-                [](void* c){delete static_cast<ClientCallbackContext::ObserveContext*>(c);}
-                );
+        OCCallbackData cbdata;
+        cbdata.context = static_cast<void*>(ctx),
+        cbdata.cb      = observeResourceCallback;
+        cbdata.cd      = [](void* c){delete (ClientCallbackContext::ObserveContext*)c;};
+
 
         OCMethod method;
         if (observeType == ObserveType::Observe)
@@ -788,7 +796,7 @@ namespace OC
 
         auto cLock = m_csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             OCHeaderOption options[MAX_HEADER_OPTIONS];
@@ -821,7 +829,7 @@ namespace OC
         OCStackResult result;
         auto cLock = m_csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             OCHeaderOption options[MAX_HEADER_OPTIONS];
@@ -863,31 +871,30 @@ namespace OC
         const std::string& host, const std::string& resourceType,
         OCConnectivityType connectivityType, SubscribeCallback& presenceHandler)
     {
-        if(!presenceHandler)
+        if (!presenceHandler)
         {
             return OC_STACK_INVALID_PARAM;
         }
 
         ClientCallbackContext::SubscribePresenceContext* ctx =
             new ClientCallbackContext::SubscribePresenceContext(presenceHandler);
-        OCCallbackData cbdata(
-                static_cast<void*>(ctx),
-                subscribePresenceCallback,
-                [](void* c)
-                {delete static_cast<ClientCallbackContext::SubscribePresenceContext*>(c);}
-                );
+        OCCallbackData cbdata;
+        cbdata.context = static_cast<void*>(ctx),
+        cbdata.cb      = subscribePresenceCallback;
+        cbdata.cd      = [](void* c){delete (ClientCallbackContext::SubscribePresenceContext*)c;};
+
 
         auto cLock = m_csdkLock.lock();
 
         std::ostringstream os;
         os << host << OC_RSRVD_PRESENCE_URI;
 
-        if(!resourceType.empty())
+        if (!resourceType.empty())
         {
             os << "?rt=" << resourceType;
         }
 
-        if(!cLock)
+        if (!cLock)
         {
             delete ctx;
             return OC_STACK_ERROR;
@@ -904,7 +911,7 @@ namespace OC
         OCStackResult result;
         auto cLock = m_csdkLock.lock();
 
-        if(cLock)
+        if (cLock)
         {
             std::lock_guard<std::recursive_mutex> lock(*cLock);
             result = OCCancel(handle, OC_LOW_QOS, NULL, 0);
@@ -928,20 +935,161 @@ namespace OC
     {
         int i = 0;
 
-        if( headerOptions.size() == 0)
+        if ( headerOptions.size() == 0)
         {
             return nullptr;
         }
 
         for (auto it=headerOptions.begin(); it != headerOptions.end(); ++it)
         {
-            options[i] = OCHeaderOption(OC_COAP_ID,
-                    it->getOptionID(),
-                    it->getOptionData().length() + 1,
-                    reinterpret_cast<const uint8_t*>(it->getOptionData().c_str()));
+            options[i] = OCHeaderOption();
+            options[i].protocolID = OC_COAP_ID;
+            options[i].optionID = it->getOptionID();
+            options[i].optionLength = it->getOptionData().length() + 1;
+            strcpy((char*)options[i].optionData, (it->getOptionData().c_str()));
             i++;
         }
 
         return options;
     }
+
+    std::shared_ptr<OCDirectPairing> cloneDevice(const OCDPDev_t* dev)
+    {
+        if (!dev)
+        {
+            return nullptr;
+        }
+
+        OCDPDev_t* result = new OCDPDev_t(*dev);
+        result->prm = new OCPrm_t[dev->prmLen];
+        memcpy(result->prm, dev->prm, sizeof(OCPrm_t)*dev->prmLen);
+        return std::shared_ptr<OCDirectPairing>(new OCDirectPairing(result));
+    }
+
+    void InProcClientWrapper::convert(const OCDPDev_t *list, PairedDevices& dpList)
+    {
+        while(list)
+        {
+            dpList.push_back(cloneDevice(list));
+            list = list->next;
+        }
+    }
+
+    OCStackResult InProcClientWrapper::FindDirectPairingDevices(unsigned short waittime,
+            GetDirectPairedCallback& callback)
+    {
+        if (!callback || 0 == waittime)
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
+
+        OCStackResult result = OC_STACK_ERROR;
+        const OCDPDev_t *list = nullptr;
+        PairedDevices dpDeviceList;
+
+        auto cLock = m_csdkLock.lock();
+
+        if (cLock)
+        {
+            std::lock_guard<std::recursive_mutex> lock(*cLock);
+
+            list = OCDiscoverDirectPairingDevices(waittime);
+            if (NULL == list)
+            {
+                result = OC_STACK_NO_RESOURCE;
+                oclog() << "findDirectPairingDevices(): No device found for direct pairing"
+                    << std::flush;
+            }
+            else {
+                convert(list, dpDeviceList);
+                std::thread exec(callback, dpDeviceList);
+                exec.detach();
+                result = OC_STACK_OK;
+            }
+        }
+        else
+        {
+            result = OC_STACK_ERROR;
+        }
+
+        return result;
+    }
+
+    OCStackResult InProcClientWrapper::GetDirectPairedDevices(GetDirectPairedCallback& callback)
+    {
+        if (!callback)
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
+
+        OCStackResult result = OC_STACK_ERROR;
+        const OCDPDev_t *list = nullptr;
+        PairedDevices dpDeviceList;
+
+        auto cLock = m_csdkLock.lock();
+
+        if (cLock)
+        {
+            std::lock_guard<std::recursive_mutex> lock(*cLock);
+
+            list = OCGetDirectPairedDevices();
+            if (NULL == list)
+            {
+                result = OC_STACK_NO_RESOURCE;
+                oclog() << "findDirectPairingDevices(): No device found for direct pairing"
+                    << std::flush;
+            }
+            else {
+                convert(list, dpDeviceList);
+                std::thread exec(callback, dpDeviceList);
+                exec.detach();
+                result = OC_STACK_OK;
+            }
+        }
+        else
+        {
+            result = OC_STACK_ERROR;
+        }
+
+        return result;
+    }
+
+    void directPairingCallback(void *ctx, OCDPDev_t *peer,
+            OCStackResult result)
+    {
+
+        ClientCallbackContext::DirectPairingContext* context =
+            static_cast<ClientCallbackContext::DirectPairingContext*>(ctx);
+
+        std::thread exec(context->callback, cloneDevice(peer), result);
+        exec.detach();
+    }
+
+    OCStackResult InProcClientWrapper::DoDirectPairing(std::shared_ptr<OCDirectPairing> peer,
+            const OCPrm_t& pmSel, const std::string& pinNumber, DirectPairingCallback& callback)
+    {
+        if (!peer || !callback)
+        {
+            oclog() << "Invalid parameters" << std::flush;
+            return OC_STACK_INVALID_PARAM;
+        }
+
+        OCStackResult result = OC_STACK_ERROR;
+        ClientCallbackContext::DirectPairingContext* context =
+            new ClientCallbackContext::DirectPairingContext(callback);
+
+        auto cLock = m_csdkLock.lock();
+        if (cLock)
+        {
+            std::lock_guard<std::recursive_mutex> lock(*cLock);
+            result = OCDoDirectPairing(static_cast<void*>(context), peer->getDev(),
+                    pmSel, const_cast<char*>(pinNumber.c_str()), directPairingCallback);
+        }
+        else
+        {
+            delete context;
+            result = OC_STACK_ERROR;
+        }
+        return result;
+    }
 }
index 522ef82..2fd1c19 100644 (file)
@@ -47,7 +47,7 @@ namespace OC
         std::mutex serverWrapperLock;
         std::map <OCResourceHandle, OC::EntityHandler>  entityHandlerMap;
         std::map <OCResourceHandle, std::string> resourceUriMap;
-        EntityHandler defaultDeviceEntityHandler = 0;
+        EntityHandler defaultDeviceEntityHandler;
     }
 }
 
@@ -59,6 +59,7 @@ void formResourceRequest(OCEntityHandlerFlag flag,
     {
         pRequest->setRequestHandle(entityHandlerRequest->requestHandle);
         pRequest->setResourceHandle(entityHandlerRequest->resource);
+        pRequest->setMessageID(entityHandlerRequest->messageID);
     }
 
     if(flag & OC_REQUEST_FLAG)
index a5e82fc..7fdc9f5 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include "ocapi.h"
+#include "OCApi.h"
+
+#if defined(_MSC_VER)
+namespace OC
+{
+    std::ostream& oclog()
+    {
+        return std::cout;
+    }
+}
+#endif
diff --git a/resource/src/OCDirectPairing.cpp b/resource/src/OCDirectPairing.cpp
new file mode 100644 (file)
index 0000000..4e50ac7
--- /dev/null
@@ -0,0 +1,85 @@
+//******************************************************************
+//
+// 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 "OCDirectPairing.h"
+#include <iomanip>
+
+namespace OC
+{
+    static const char COAP[] = "coap://";
+    static const char COAPS[] = "coaps://";
+    static const int UUID_LENGTH = (128/8); //UUID length
+
+    OCDirectPairing::OCDirectPairing(OCDPDev_t *ptr):m_devPtr(ptr)
+    {
+    }
+
+    std::string OCDirectPairing::getHost()
+    {
+        bool ipv6 = false;
+        std::ostringstream host("");
+        if (m_devPtr->connType & CT_IP_USE_V6)
+        {
+            ipv6 = true;
+        }
+
+        host << COAPS << (ipv6?"[":"") << m_devPtr->endpoint.addr;
+        host << (ipv6?"]:":":") << m_devPtr->securePort;
+
+        return host.str();
+    }
+
+    std::string OCDirectPairing::getDeviceID()
+    {
+        std::ostringstream deviceId("");
+
+        for (int i = 0; i < UUID_LENGTH; i++)
+        {
+            if (i == 4 || i == 6 || i == 8 || i == 10)
+            {
+                deviceId << '-';
+            }
+            deviceId << std::hex << std::setfill('0') << std::setw(2) << static_cast<unsigned>(m_devPtr->deviceID.id[i]);
+        }
+
+        return deviceId.str();
+    }
+
+    std::vector<OCPrm_t> OCDirectPairing::getPairingMethods()
+    {
+        std::vector<OCPrm_t> prms;
+
+        for (size_t i = 0; i < m_devPtr->prmLen; i++)
+        {
+            prms.push_back(m_devPtr->prm[i]);
+        }
+        return prms;
+    }
+
+    OCConnectivityType OCDirectPairing::getConnType()
+    {
+        return m_devPtr->connType;
+    }
+
+    OCDPDev_t* OCDirectPairing::getDev()
+    {
+        return m_devPtr;
+    }
+}
index cdbb0e7..e199f5d 100644 (file)
@@ -97,6 +97,8 @@ std::string OC::OCException::reason(const OCStackResult sr)
             return OC::Exception::INVALID_REPRESENTATION;
         case OC_STACK_UNAUTHORIZED_REQ:
             return OC::Exception::UNAUTHORIZED_REQUEST;
+        case OC_STACK_TOO_LARGE_REQ:
+            return OC::Exception::TOO_LARGE_REQ;
         case OC_STACK_PDM_IS_NOT_INITIALIZED:
             return OC::Exception::PDM_DB_NOT_INITIALIZED;
         case OC_STACK_DUPLICATE_UUID:
index e2e7aa5..b722750 100644 (file)
@@ -43,7 +43,7 @@ namespace OC
         }
 
         OCStackResult notifyAllObservers(OCResourceHandle resourceHandle,
-                                                QualityOfService QoS)
+                                     QualityOfService QoS)
         {
             return OCPlatform_impl::Instance().notifyAllObservers(resourceHandle, QoS);
         }
@@ -54,52 +54,52 @@ namespace OC
         }
 
         OCStackResult notifyListOfObservers(OCResourceHandle resourceHandle,
-                                                ObservationIds& observationIds,
-                                                const std::shared_ptr<OCResourceResponse> pResponse)
+                                     ObservationIds& observationIds,
+                                     const std::shared_ptr<OCResourceResponse> pResponse)
         {
             return OCPlatform_impl::Instance().notifyListOfObservers(resourceHandle,
-                                                observationIds, pResponse);
+                                     observationIds, pResponse);
         }
 
         OCStackResult notifyListOfObservers(OCResourceHandle resourceHandle,
-                                                ObservationIds& observationIds,
-                                                const std::shared_ptr<OCResourceResponse> pResponse,
-                                                QualityOfService QoS)
+                                     ObservationIds& observationIds,
+                                     const std::shared_ptr<OCResourceResponse> pResponse,
+                                     QualityOfService QoS)
         {
             return OCPlatform_impl::Instance().notifyListOfObservers(resourceHandle,
-                                                    observationIds, pResponse, QoS);
+                                     observationIds, pResponse, QoS);
         }
 
         OCResource::Ptr constructResourceObject(const std::string& host,
-                                                const std::string& uri,
-                                                OCConnectivityType connectivityType,
-                                                bool isObservable,
-                                                const std::vector<std::string>& resourceTypes,
-                                                const std::vector<std::string>& interfaces)
+                                     const std::string& uri,
+                                     OCConnectivityType connectivityType,
+                                     bool isObservable,
+                                     const std::vector<std::string>& resourceTypes,
+                                     const std::vector<std::string>& interfaces)
         {
             return OCPlatform_impl::Instance().constructResourceObject(host,
-                                                uri, connectivityType,
-                                                isObservable,
-                                                resourceTypes, interfaces);
+                                     uri, connectivityType,
+                                     isObservable,
+                                     resourceTypes, interfaces);
         }
 
         OCStackResult findResource(const std::string& host,
-                                            const std::string& resourceName,
-                                            OCConnectivityType connectivityType,
-                                            FindCallback resourceHandler)
+                                 const std::string& resourceName,
+                                 OCConnectivityType connectivityType,
+                                 FindCallback resourceHandler)
         {
             return OCPlatform_impl::Instance().findResource(host, resourceName,
-                                    connectivityType, resourceHandler);
+                                 connectivityType, resourceHandler);
         }
 
         OCStackResult findResource(const std::string& host,
-                                            const std::string& resourceName,
-                                            OCConnectivityType connectivityType,
-                                            FindCallback resourceHandler,
-                                            QualityOfService QoS)
+                                 const std::string& resourceName,
+                                 OCConnectivityType connectivityType,
+                                 FindCallback resourceHandler,
+                                 QualityOfService QoS)
         {
             return OCPlatform_impl::Instance().findResource(host, resourceName,
-                                    connectivityType, resourceHandler, QoS);
+                                 connectivityType, resourceHandler, QoS);
         }
 
         OCStackResult findResource(const std::string& host,
@@ -124,57 +124,57 @@ namespace OC
         }
 
         OCStackResult getDeviceInfo(const std::string& host,
-                                            const std::string& deviceURI,
-                                            OCConnectivityType connectivityType,
-                                            FindDeviceCallback deviceInfoHandler)
+                                 const std::string& deviceURI,
+                                 OCConnectivityType connectivityType,
+                                 FindDeviceCallback deviceInfoHandler)
         {
             return OCPlatform_impl::Instance().getDeviceInfo(host, deviceURI,
-                   connectivityType, deviceInfoHandler);
+                                 connectivityType, deviceInfoHandler);
         }
 
         OCStackResult getDeviceInfo(const std::string& host,
-                                            const std::string& deviceURI,
-                                            OCConnectivityType connectivityType,
-                                            FindDeviceCallback deviceInfoHandler,
-                                            QualityOfService QoS)
+                                 const std::string& deviceURI,
+                                 OCConnectivityType connectivityType,
+                                 FindDeviceCallback deviceInfoHandler,
+                                 QualityOfService QoS)
         {
             return OCPlatform_impl::Instance().getDeviceInfo(host, deviceURI, connectivityType,
-                    deviceInfoHandler, QoS);
+                                 deviceInfoHandler, QoS);
         }
 
         OCStackResult getPlatformInfo(const std::string& host,
-                                                const std::string& platformURI,
-                                                OCConnectivityType connectivityType,
-                                                FindPlatformCallback platformInfoHandler)
+                                 const std::string& platformURI,
+                                 OCConnectivityType connectivityType,
+                                 FindPlatformCallback platformInfoHandler)
         {
             return OCPlatform_impl::Instance().getPlatformInfo(host, platformURI,
-                   connectivityType, platformInfoHandler);
+                                 connectivityType, platformInfoHandler);
         }
 
         OCStackResult getPlatformInfo(const std::string& host,
-                                                const std::string& platformURI,
-                                                OCConnectivityType connectivityType,
-                                                FindPlatformCallback platformInfoHandler,
-                                                QualityOfService QoS)
+                                 const std::string& platformURI,
+                                 OCConnectivityType connectivityType,
+                                 FindPlatformCallback platformInfoHandler,
+                                 QualityOfService QoS)
         {
             return OCPlatform_impl::Instance().getPlatformInfo(host, platformURI, connectivityType,
-                    platformInfoHandler, QoS);
+                                 platformInfoHandler, QoS);
         }
 
         OCStackResult registerResource(OCResourceHandle& resourceHandle,
-                                                std::string& resourceURI,
-                                                const std::string& resourceTypeName,
-                                                const std::string& resourceInterface,
-                                                EntityHandler entityHandler,
-                                                uint8_t resourceProperty)
+                                 std::string& resourceURI,
+                                 const std::string& resourceTypeName,
+                                 const std::string& resourceInterface,
+                                 EntityHandler entityHandler,
+                                 uint8_t resourceProperty)
         {
             return OCPlatform_impl::Instance().registerResource(resourceHandle, resourceURI,
-                                                resourceTypeName, resourceInterface,
-                                                entityHandler, resourceProperty);
+                                 resourceTypeName, resourceInterface,
+                                 entityHandler, resourceProperty);
         }
 
         OCStackResult registerResource(OCResourceHandle& resourceHandle,
-                                                const std::shared_ptr< OCResource > resource)
+                                 const std::shared_ptr< OCResource > resource)
         {
             return OCPlatform_impl::Instance().registerResource(resourceHandle, resource);
         }
@@ -195,42 +195,41 @@ namespace OC
         }
 
         OCStackResult unbindResource(OCResourceHandle collectionHandle,
-                                                OCResourceHandle resourceHandle)
+                                 OCResourceHandle resourceHandle)
         {
             return OCPlatform_impl::Instance().unbindResource(collectionHandle, resourceHandle);
         }
 
         OCStackResult unbindResources(const OCResourceHandle collectionHandle,
-                                                const std::vector<OCResourceHandle>& resourceHandles
-                                                )
+                                 const std::vector<OCResourceHandle>& resourceHandles)
         {
             return OCPlatform_impl::Instance().unbindResources(collectionHandle, resourceHandles);
         }
 
         OCStackResult bindResource(const OCResourceHandle collectionHandle,
-                                                const OCResourceHandle resourceHandle)
+                                 const OCResourceHandle resourceHandle)
         {
             return OCPlatform_impl::Instance().bindResource(collectionHandle, resourceHandle);
         }
 
         OCStackResult bindResources(const OCResourceHandle collectionHandle,
-                                                const std::vector<OCResourceHandle>& resourceHandles
-                                                )
+                                 const std::vector<OCResourceHandle>& resourceHandles
+                                 )
         {
             return OCPlatform_impl::Instance().bindResources(collectionHandle, resourceHandles);
         }
 
         OCStackResult bindTypeToResource(const OCResourceHandle& resourceHandle,
-                                                const std::string& resourceTypeName)
+                                 const std::string& resourceTypeName)
         {
             return OCPlatform_impl::Instance().bindTypeToResource(resourceHandle,resourceTypeName);
         }
 
         OCStackResult bindInterfaceToResource(const OCResourceHandle& resourceHandle,
-                                                const std::string& resourceInterfaceName)
+                                 const std::string& resourceInterfaceName)
         {
             return OCPlatform_impl::Instance().bindInterfaceToResource(resourceHandle,
-                                                resourceInterfaceName);
+                                                             resourceInterfaceName);
         }
 
         OCStackResult startPresence(const unsigned int announceDurationSeconds)
@@ -244,22 +243,22 @@ namespace OC
         }
 
         OCStackResult subscribePresence(OCPresenceHandle& presenceHandle,
-                                                const std::string& host,
-                                                OCConnectivityType connectivityType,
-                                                SubscribeCallback presenceHandler)
+                                     const std::string& host,
+                                     OCConnectivityType connectivityType,
+                                     SubscribeCallback presenceHandler)
         {
             return OCPlatform_impl::Instance().subscribePresence(presenceHandle, host,
-                                                connectivityType, presenceHandler);
+                                                             connectivityType, presenceHandler);
         }
 
         OCStackResult subscribePresence(OCPresenceHandle& presenceHandle,
-                                                const std::string& host,
-                                                const std::string& resourceType,
-                                                OCConnectivityType connectivityType,
-                                                SubscribeCallback presenceHandler)
+                                     const std::string& host,
+                                     const std::string& resourceType,
+                                     OCConnectivityType connectivityType,
+                                     SubscribeCallback presenceHandler)
         {
             return OCPlatform_impl::Instance().subscribePresence(presenceHandle, host,
-                                                resourceType, connectivityType, presenceHandler);
+                                             resourceType, connectivityType, presenceHandler);
         }
 
         OCStackResult unsubscribePresence(OCPresenceHandle presenceHandle)
@@ -271,6 +270,27 @@ namespace OC
         {
             return OCPlatform_impl::Instance().sendResponse(pResponse);
         }
+
+        OCStackResult findDirectPairingDevices(unsigned short waittime,
+                                         GetDirectPairedCallback directPairingHandler)
+        {
+            return OCPlatform_impl::Instance().findDirectPairingDevices(waittime,
+                                         directPairingHandler);
+        }
+
+        OCStackResult getDirectPairedDevices(GetDirectPairedCallback directPairingHandler)
+        {
+            return OCPlatform_impl::Instance().getDirectPairedDevices(directPairingHandler);
+        }
+
+        OCStackResult doDirectPairing(std::shared_ptr<OCDirectPairing> peer, OCPrm_t pmSel,
+                                 const std::string& pinNumber,
+                                 DirectPairingCallback resultCallback)
+        {
+            return OCPlatform_impl::Instance().doDirectPairing(peer, pmSel,
+                                             pinNumber, resultCallback);
+        }
+
     } // namespace OCPlatform
 } //namespace OC
 
index 059944c..03fa1d9 100644 (file)
@@ -387,5 +387,31 @@ namespace OC
     {
         return m_csdkLock;
     }
+
+    OCStackResult OCPlatform_impl::findDirectPairingDevices(unsigned short waittime,
+                             GetDirectPairedCallback directPairingHandler)
+    {
+        return checked_guard(m_client, &IClientWrapper::FindDirectPairingDevices,
+                             waittime, directPairingHandler);
+
+    }
+
+    OCStackResult OCPlatform_impl::getDirectPairedDevices(
+                             GetDirectPairedCallback directPairingHandler)
+    {
+
+        return checked_guard(m_client, &IClientWrapper::GetDirectPairedDevices,
+                             directPairingHandler);
+    }
+
+    OCStackResult OCPlatform_impl::doDirectPairing(std::shared_ptr<OCDirectPairing> peer,
+                             OCPrm_t pmSel,
+                             const std::string& pinNumber,
+                             DirectPairingCallback resultCallback)
+    {
+        return checked_guard(m_client, &IClientWrapper::DoDirectPairing,
+                             peer, pmSel, pinNumber, resultCallback);
+    }
+
 } //namespace OC
 
index 8b0015b..06b2083 100644 (file)
@@ -82,9 +82,10 @@ namespace OC
         rep[OC_RSRVD_SPEC_VERSION] = payload->specVersion ?
             std::string(payload->specVersion) :
             std::string();
-        rep[OC_RSRVD_DATA_MODEL_VERSION] = payload->dataModelVersion ?
-            std::string(payload->dataModelVersion) :
-            std::string();
+        for (OCStringLL *strll = payload->dataModelVersions; strll; strll = strll->next)
+        {
+            rep.addDataModelVersion(strll->value);
+        }
         for (OCStringLL *strll = payload->types; strll; strll = strll->next)
         {
            rep.addResourceType(strll->value);
@@ -134,9 +135,9 @@ namespace OC
             std::string(payload->info.systemTime) :
             std::string();
 
-        if (payload->rt)
+        for (OCStringLL *strll = payload->rt; strll; strll = strll->next)
         {
-            rep.addResourceType(payload->rt);
+            rep.addResourceType(strll->value);
         }
         for (OCStringLL *strll = payload->interfaces; strll; strll = strll->next)
         {
@@ -314,11 +315,13 @@ namespace OC
         ((int64_t*)array)[pos] = item;
     }
 
+#if !defined(_MSC_VER)
     template<>
     void get_payload_array::copy_to_array(std::_Bit_reference br, void* array, size_t pos)
     {
         ((bool*)array)[pos] = static_cast<bool>(br);
     }
+#endif
 
     template<>
     void get_payload_array::copy_to_array(std::string item, void* array, size_t pos)
@@ -755,6 +758,16 @@ namespace OC
         m_interfaces = resourceInterfaces;
     }
 
+    const std::vector<std::string>& OCRepresentation::getDataModelVersions() const
+    {
+        return m_dataModelVersions;
+    }
+
+    void OCRepresentation::addDataModelVersion(const std::string& str)
+    {
+        m_dataModelVersions.push_back(str);
+    }
+
     bool OCRepresentation::hasAttribute(const std::string& str) const
     {
         return m_values.find(str) != m_values.end();
@@ -775,7 +788,8 @@ namespace OC
         else if ((m_interfaceType == InterfaceType::None
                         || m_interfaceType==InterfaceType::DefaultChild
                         || m_interfaceType==InterfaceType::LinkChild)
-                    && (m_resourceTypes.size()>0 || m_interfaces.size()>0))
+                    && (m_resourceTypes.size()>0 || m_interfaces.size()>0
+                        || m_dataModelVersions.size()>0))
         {
             return false;
         }
@@ -891,13 +905,13 @@ namespace OC
         // contains the inner most vector-type
         typedef T base_type;
         // contains the AttributeType for this item
-        constexpr static AttributeType enum_type =
+        BOOST_STATIC_CONSTEXPR AttributeType enum_type =
             AttributeTypeConvert<T>::type;
         // contains the AttributeType for this base-type
-        constexpr static AttributeType enum_base_type =
+        BOOST_STATIC_CONSTEXPR AttributeType enum_base_type =
             AttributeTypeConvert<T>::type;
         // depth of the vector
-        constexpr static size_t depth = 0;
+        BOOST_STATIC_CONSTEXPR size_t depth = 0;
     };
 
     template<typename T>
@@ -911,10 +925,10 @@ namespace OC
     {
         typedef T type;
         typedef typename type_info<typename T::value_type>::base_type base_type;
-        constexpr static AttributeType enum_type = AttributeType::Vector;
-        constexpr static AttributeType enum_base_type =
+        BOOST_STATIC_CONSTEXPR AttributeType enum_type = AttributeType::Vector;
+        BOOST_STATIC_CONSTEXPR AttributeType enum_base_type =
             type_info<typename T::value_type>::enum_base_type;
-        constexpr static size_t depth = 1 +
+        BOOST_STATIC_CONSTEXPR size_t depth = 1 +
             type_info<typename T::value_type>::depth;
     };
 
@@ -924,9 +938,9 @@ namespace OC
     {
         typedef std::vector<uint8_t> type;
         typedef std::vector<uint8_t> base_type;
-        constexpr static AttributeType enum_type = AttributeType::Binary;
-        constexpr static AttributeType enum_base_type = AttributeType::Binary;
-        constexpr static size_t depth = 0;
+        BOOST_STATIC_CONSTEXPR AttributeType enum_type = AttributeType::Binary;
+        BOOST_STATIC_CONSTEXPR AttributeType enum_base_type = AttributeType::Binary;
+        BOOST_STATIC_CONSTEXPR size_t depth = 0;
     };
 
 
index a3c8ec8..c0601eb 100644 (file)
 
 #include <boost/lexical_cast.hpp>
 #include <sstream>
+#ifdef HAVE_ARPA_INET_H
 #include <arpa/inet.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_IN6ADDR_H
+#include <in6addr.h>
+#endif
 
 namespace OC {
 
 static const char COAP[] = "coap://";
 static const char COAPS[] = "coaps://";
 static const char COAP_TCP[] = "coap+tcp://";
+static const char COAP_GATT[] = "coap+gatt://";
+static const char COAP_RFCOMM[] = "coap+rfcomm://";
 
 using OC::nil_guard;
 using OC::result_guard;
@@ -67,15 +77,15 @@ OCResource::OCResource(std::weak_ptr<IClientWrapper> clientWrapper,
                         const std::vector<std::string>& interfaces)
  :  m_clientWrapper(clientWrapper), m_uri(uri),
     m_resourceId(serverId, m_uri),
-    m_devAddr{ OC_DEFAULT_ADAPTER, OC_DEFAULT_FLAGS, 0, {0}, 0
-#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
-    , {0}
-#endif
-    },
     m_isObservable(observable), m_isCollection(false),
     m_resourceTypes(resourceTypes), m_interfaces(interfaces),
     m_observeHandle(nullptr)
 {
+    m_devAddr = OCDevAddr{OC_DEFAULT_ADAPTER, OC_DEFAULT_FLAGS, 0, {0}, 0,
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
+                          {0}
+#endif
+                        };
     m_isCollection = std::find(m_interfaces.begin(), m_interfaces.end(), LINK_INTERFACE)
                         != m_interfaces.end();
 
@@ -122,19 +132,27 @@ void OCResource::setHost(const std::string& host)
     else if(host.compare(0, sizeof(COAPS) - 1, COAPS) == 0)
     {
         prefix_len = sizeof(COAPS) - 1;
-        m_devAddr.flags = static_cast<OCTransportFlags>(m_devAddr.flags & OC_SECURE);
+        m_devAddr.flags = static_cast<OCTransportFlags>(m_devAddr.flags | OC_SECURE);
     }
     else if (host.compare(0, sizeof(COAP_TCP) - 1, COAP_TCP) == 0)
     {
         prefix_len = sizeof(COAP_TCP) - 1;
     }
+    else if (host.compare(0, sizeof(COAP_GATT) - 1, COAP_GATT) == 0)
+    {
+        prefix_len = sizeof(COAP_GATT) - 1;
+    }
+    else if (host.compare(0, sizeof(COAP_RFCOMM) - 1, COAP_RFCOMM) == 0)
+    {
+        prefix_len = sizeof(COAP_RFCOMM) - 1;
+    }
     else
     {
         throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
             m_interfaces.empty(), m_clientWrapper.expired(), false, false);
     }
 
-    // remove 'coap://' or 'coaps://' or 'coap+tcp://'
+    // remove 'coap://' or 'coaps://' or 'coap+tcp://' or 'coap+gatt://' or 'coap+rfcomm://'
     std::string host_token = host.substr(prefix_len);
 
     if(host_token[0] == '[') // IPv6
@@ -456,7 +474,7 @@ OCStackResult OCResource::cancelObserve(QualityOfService QoS)
 
     OCStackResult result =  checked_guard(m_clientWrapper.lock(),
             &IClientWrapper::CancelObserveResource,
-            m_observeHandle, "", m_uri, m_headerOptions, QoS);
+            m_observeHandle, (const char*)"", m_uri, m_headerOptions, QoS);
 
     if(result == OC_STACK_OK)
     {
@@ -479,20 +497,31 @@ void OCResource::unsetHeaderOptions()
 std::string OCResource::host() const
 {
     std::ostringstream ss;
-    if (m_devAddr.flags & OC_SECURE)
+
+    if (m_devAddr.adapter & OC_ADAPTER_TCP)
     {
-        ss << COAPS;
+        ss << COAP_TCP;
     }
-    else if ((m_devAddr.adapter & OC_ADAPTER_TCP)
-            || (m_devAddr.adapter & OC_ADAPTER_GATT_BTLE)
-            || (m_devAddr.adapter & OC_ADAPTER_RFCOMM_BTEDR))
+    else if (m_devAddr.adapter & OC_ADAPTER_GATT_BTLE)
     {
-        ss << COAP_TCP;
+        ss << COAP_GATT;
+    }
+    else if (m_devAddr.adapter & OC_ADAPTER_RFCOMM_BTEDR)
+    {
+        ss << COAP_RFCOMM;
     }
     else
     {
-        ss << COAP;
+        if (m_devAddr.flags & OC_SECURE)
+        {
+            ss << COAPS;
+        }
+        else
+        {
+            ss << COAP;
+        }
     }
+
     if (m_devAddr.flags & OC_IP_USE_V6)
     {
         ss << '[' << m_devAddr.addr << ']';
index f1106a1..146e2eb 100644 (file)
 ##
 Import('env')
 
+import os
+
 # Add third party libraries
 lib_env = env.Clone()
 SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env')
 
 oclib_env = lib_env.Clone()
+secured = lib_env.get('SECURED')
 ######################################################################
 # Build flags
 ######################################################################
@@ -43,17 +46,17 @@ oclib_env.AppendUnique(CPPPATH = [
 
 oclib_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 
-oclib_env.AppendUnique(LIBS = ['octbstack', 'oc_logger'])
-oclib_env.AppendUnique(LIBS = ['connectivity_abstraction'])
+oclib_env.AppendUnique(LIBS = ['oc_logger'])
+oclib_env.PrependUnique(LIBS = ['octbstack', 'connectivity_abstraction', 'ocsrm'])
 
 target_os = env.get('TARGET_OS')
 if target_os == 'linux':
        oclib_env.AppendUnique(LIBS = ['pthread'])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
        oclib_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-fPIC'])
 
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
        oclib_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
 
 if target_os == 'android':
@@ -67,6 +70,14 @@ if target_os == 'tizen':
 if target_os in ['linux'] and env.get('SIMULATOR', False):
     oclib_env.Append( RPATH = env.Literal('\\$$ORIGIN'))
 
+if target_os in ['msys_nt', 'windows']:
+       oclib_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'oc_logger')])
+       oclib_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk')])
+       oclib_env.AppendUnique(LIBS=['octbstack', 'logger', 'oc_logger','connectivity_abstraction', 'ocsrm', 'c_common', 'routingmanager'])
+       oclib_env.AppendUnique(LIBS=[ 'coap', 'ws2_32' ,'iphlpapi'])
+       if secured == '1':
+               oclib_env.AppendUnique(LIBS=['tinydtls'])
+
 ######################################################################
 # Source files and Targets
 ######################################################################
@@ -80,13 +91,18 @@ oclib_src = [
                'InProcServerWrapper.cpp',
                'InProcClientWrapper.cpp',
                'OCResourceRequest.cpp',
-               'CAManager.cpp'
+               'CAManager.cpp',
+               'OCDirectPairing.cpp'
        ]
 
-oclib = oclib_env.SharedLibrary('oc', oclib_src)
-oclib_env.InstallTarget(oclib, 'liboc')
-oclib_env.UserInstallTargetLib(oclib, 'liboc')
-
+if target_os in ['windows']:
+       oclib_src = oclib_src + ['OCApi.cpp']
+       # TODO: Add OC_EXPORT prefixes to enable DLL generation
+       oclib = oclib_env.StaticLibrary('oc', oclib_src)
+else:
+       oclib = oclib_env.SharedLibrary('oc', oclib_src)
+oclib_env.InstallTarget(oclib, 'oc')
+oclib_env.UserInstallTargetLib(oclib, 'oc')
 header_dir = env.get('SRC_DIR') + '/resource/include/'
 
 oclib_env.UserInstallTargetHeader(header_dir + 'OCApi.h', 'resource', 'OCApi.h')
@@ -115,6 +131,7 @@ oclib_env.UserInstallTargetHeader(header_dir + 'OCResourceResponse.h', 'resource
 oclib_env.UserInstallTargetHeader(header_dir + 'OCUtilities.h', 'resource', 'OCUtilities.h')
 
 oclib_env.UserInstallTargetHeader(header_dir + 'CAManager.h', 'resource', 'CAManager.h')
+oclib_env.UserInstallTargetHeader(header_dir + 'OCDirectPairing.h', 'resource', 'OCDirectPairing.h')
 
 # Add Provisioning library
 if target_os in ['linux', 'android', 'tizen'] and env.get('SECURED') == '1':
index 94495ba..b78a5ed 100644 (file)
@@ -68,6 +68,10 @@ if target_os == 'android':
                # Too much boost warning, suppress the warning
                lib_env.AppendUnique(CCFLAGS = ['-w'])
 
+elif target_os in ['windows']:
+       SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'boost', 'SConscript'))
+       boost_path = os.path.join(src_dir,'extlibs','boost','boost')
+       lib_env.AppendUnique(CPPPATH = [boost_path])
 elif target_os == 'ios':
        lib_env.AppendUnique(FRAMEWORKS = ['boost'])
 elif target_os == 'darwin':
index 08a9ffb..50a38cc 100644 (file)
@@ -60,7 +60,7 @@ if target_os == 'linux':
                SConscript('csdk/security/provisioning/unittest/SConscript')
                SConscript('provisioning/unittests/SConscript')
 
-elif target_os == 'darwin':
+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(src_dir + '/extlibs/gtest/SConscript')
@@ -69,4 +69,18 @@ elif target_os == 'darwin':
        SConscript('csdk/stack/test/SConscript')
        SConscript('csdk/connectivity/test/SConscript')
 
+       # Build Security Resource Manager unit tests
+       SConscript('csdk/security/unittest/SConscript')
 
+       # Build Provisioning API unit test
+       if env.get('SECURED') == '1':
+               SConscript('csdk/security/provisioning/unittest/SConscript')
+
+elif target_os in ['darwin', 'msys_nt']:
+       # Verify that 'google unit test' library is installed.  If not,
+       # get it and install it
+       SConscript(src_dir + '/extlibs/gtest/SConscript')
+
+       # Build C stack's unit tests.
+       SConscript('csdk/stack/test/SConscript')
+       SConscript('csdk/connectivity/test/SConscript')
index efe51dd..d6b7ef1 100644 (file)
@@ -64,6 +64,7 @@ namespace OC
                 OC_STACK_INVALID_DEVICE_INFO,
                 OC_STACK_INVALID_JSON,
                 OC_STACK_UNAUTHORIZED_REQ,
+                OC_STACK_TOO_LARGE_REQ,
                 OC_STACK_PRESENCE_STOPPED,
                 OC_STACK_PRESENCE_TIMEOUT,
                 OC_STACK_PRESENCE_DO_NOT_HANDLE,
@@ -107,6 +108,7 @@ namespace OC
                 OC::Exception::INVALID_DEVICE_INFO,
                 OC::Exception::INVALID_REPRESENTATION,
                 OC::Exception::UNAUTHORIZED_REQUEST,
+                OC::Exception::TOO_LARGE_REQ,
                 OC::Exception::PRESENCE_STOPPED,
                 OC::Exception::PRESENCE_TIMEOUT,
                 OC::Exception::PRESENCE_NOT_HANDLED,
index f2db5df..d5aad2e 100644 (file)
@@ -62,6 +62,14 @@ namespace OCPlatformTest
     {
     }
 
+    void directPairHandler(std::shared_ptr<OCDirectPairing> /*dev*/, OCStackResult /*res*/)
+    {
+    }
+
+    void pairedHandler(const PairedDevices& /*list*/)
+    {
+    }
+
     //Helper methods
     void DeleteStringLL(OCStringLL* ll)
     {
@@ -79,7 +87,8 @@ namespace OCPlatformTest
     {
         delete[] deviceInfo.deviceName;
         DeleteStringLL(deviceInfo.types);
-
+        delete[] deviceInfo.specVersion;
+        DeleteStringLL(deviceInfo.dataModelVersions);
     }
 
     void DuplicateString(char ** targetString, std::string sourceString)
@@ -740,13 +749,16 @@ namespace OCPlatformTest
         deviceInfo.types = NULL;
         OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.wk.d");
         OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.d.tv");
+        DuplicateString(&deviceInfo.specVersion, "mySpecVersion");
+        deviceInfo.dataModelVersions = nullptr;
+        OCResourcePayloadAddStringLL(&deviceInfo.dataModelVersions, "myDataModelVersions");
         EXPECT_EQ(OC_STACK_OK, OCPlatform::registerDeviceInfo(deviceInfo));
         EXPECT_NO_THROW(DeleteDeviceInfo(deviceInfo));
     }
 
     TEST(RegisterDeviceInfoTest, RegisterDeviceInfoWithEmptyObject)
     {
-        OCDeviceInfo di = {0, 0};
+        OCDeviceInfo di = {0, 0, 0, 0};
         EXPECT_ANY_THROW(OCPlatform::registerDeviceInfo(di));
     }
 
@@ -815,4 +827,46 @@ namespace OCPlatformTest
                 OC_MULTICAST_IP, CT_DEFAULT, &presenceHandler));
         EXPECT_EQ(OC_STACK_OK, OCPlatform::unsubscribePresence(presenceHandle));
     }
+
+    TEST(FindDirectPairingTest, FindDirectPairingNullCallback)
+    {
+        EXPECT_ANY_THROW(OCPlatform::findDirectPairingDevices(1, nullptr));
+    }
+
+    TEST(FindDirectPairingTest, FindDirectPairingZeroTimeout)
+    {
+        EXPECT_ANY_THROW(OCPlatform::findDirectPairingDevices(0, &pairedHandler));
+    }
+
+    TEST(GetDirectPairedTest, GetDirectPairedNullCallback)
+    {
+        EXPECT_ANY_THROW(OCPlatform::getDirectPairedDevices(nullptr));
+    }
+
+    TEST(DoDirectPairingTest, DoDirectPairingNullCallback)
+    {
+        OCDPDev_t peer;
+        OCPrm_t pmSel = DP_PRE_CONFIGURED;
+        std::string pin("");
+        std::shared_ptr<OCDirectPairing> s_dp(new OCDirectPairing(&peer));
+        EXPECT_ANY_THROW(OCPlatform::doDirectPairing(s_dp, pmSel, pin, nullptr));
+    }
+
+    TEST(DoDirectPairingTest, DoDirectPairingNullPeer)
+    {
+        OCDPDev_t peer;
+        OCPrm_t pmSel = DP_PRE_CONFIGURED;
+        std::string pin("");
+        std::shared_ptr<OCDirectPairing> s_dp(new OCDirectPairing(&peer));
+        EXPECT_ANY_THROW(OCPlatform::doDirectPairing(nullptr, pmSel, pin, &directPairHandler));
+    }
+
+    TEST(DoDirectPairingTest, DoDirectPairingNullPeerNullCallback)
+    {
+        OCDPDev_t peer;
+        OCPrm_t pmSel = DP_PRE_CONFIGURED;
+        std::string pin("");
+        std::shared_ptr<OCDirectPairing> s_dp(new OCDirectPairing(&peer));
+        EXPECT_ANY_THROW(OCPlatform::doDirectPairing(nullptr, pmSel, pin, nullptr));
+    }
 }
index 8c827c1..5e177be 100644 (file)
@@ -52,7 +52,7 @@ namespace OCRepresentationEncodingTest
     static const char sid1[] = "646F6F72-4465-7669-6365-555549443030";
     static const char devicename1[] = "device name";
     static const char specver1[] = "spec version";
-    static const char dmver1[] = "data model version";
+    static const char dmver1[] = "res.1.1.0";
     static OCStringLL *types = NULL;
     // Device Payloads
     TEST(DeviceDiscoveryEncoding, Normal)
@@ -66,11 +66,14 @@ namespace OCRepresentationEncodingTest
                 types,
                 specver1,
                 dmver1);
+        EXPECT_TRUE(device);
         EXPECT_STREQ(sid1, device->sid);
         EXPECT_STREQ(devicename1, device->deviceName);
         EXPECT_STREQ(specver1, device->specVersion);
-        EXPECT_STREQ(dmver1, device->dataModelVersion);
-        EXPECT_EQ(PAYLOAD_TYPE_DEVICE, ((OCPayload*)device)->type);
+        EXPECT_TRUE(device->dataModelVersions);
+        EXPECT_STREQ("res.1.1.0", device->dataModelVersions->value);
+        EXPECT_FALSE(device->dataModelVersions->next);
+        EXPECT_EQ(PAYLOAD_TYPE_DEVICE, ((OCPayload *)device)->type);
         EXPECT_STREQ("oic.wk.d", device->types->value);
         EXPECT_STREQ("oic.d.tv", device->types->next->value);
 
@@ -85,21 +88,51 @@ namespace OCRepresentationEncodingTest
         EXPECT_STREQ(device->sid, ((OCDevicePayload*)parsedDevice)->sid);
         EXPECT_STREQ(device->deviceName, ((OCDevicePayload*)parsedDevice)->deviceName);
         EXPECT_STREQ(device->specVersion, ((OCDevicePayload*)parsedDevice)->specVersion);
-        EXPECT_STREQ(device->dataModelVersion, ((OCDevicePayload*)parsedDevice)->dataModelVersion);
+        EXPECT_STREQ(device->dataModelVersions->value, ((OCDevicePayload*)parsedDevice)->dataModelVersions->value);
         EXPECT_STREQ("oic.wk.d", ((OCDevicePayload*)parsedDevice)->types->value);
         EXPECT_STREQ("oic.d.tv", ((OCDevicePayload*)parsedDevice)->types->next->value);
         EXPECT_EQ(device->base.type, ((OCDevicePayload*)parsedDevice)->base.type);
 
         OCPayloadDestroy((OCPayload*)device);
 
-        OC::MessageContainer mc;
-        mc.setPayload(parsedDevice);
-        EXPECT_EQ(1u, mc.representations().size());
-        const OC::OCRepresentation& r = mc.representations()[0];
-        EXPECT_STREQ(sid1, r.getValue<std::string>(OC_RSRVD_DEVICE_ID).c_str());
-        EXPECT_STREQ(devicename1, r.getValue<std::string>(OC_RSRVD_DEVICE_NAME).c_str());
-        EXPECT_STREQ(specver1, r.getValue<std::string>(OC_RSRVD_SPEC_VERSION).c_str());
-        EXPECT_STREQ(dmver1, r.getValue<std::string>(OC_RSRVD_DATA_MODEL_VERSION).c_str());
+        OC::MessageContainer mc1;
+        mc1.setPayload(parsedDevice);
+        EXPECT_EQ(1u, mc1.representations().size());
+        const OC::OCRepresentation &r1 = mc1.representations()[0];
+        EXPECT_STREQ(sid1, r1.getValue<std::string>(OC_RSRVD_DEVICE_ID).c_str());
+        EXPECT_STREQ(devicename1, r1.getValue<std::string>(OC_RSRVD_DEVICE_NAME).c_str());
+        EXPECT_STREQ(specver1, r1.getValue<std::string>(OC_RSRVD_SPEC_VERSION).c_str());
+        EXPECT_STREQ("res.1.1.0", r1.getDataModelVersions()[0].c_str());
+
+        OCPayloadDestroy(parsedDevice);
+
+        static const char dmver2[] = "res.1.1.0,sh.1.1.0";
+        device = OCDevicePayloadCreate(
+                     sid1,
+                     devicename1,
+                     types,
+                     specver1,
+                     dmver2);
+
+        EXPECT_STREQ("res.1.1.0", device->dataModelVersions->value);
+        EXPECT_TRUE(device->dataModelVersions->next);
+        EXPECT_STREQ("sh.1.1.0", device->dataModelVersions->next->value);
+        EXPECT_FALSE(device->dataModelVersions->next->next);
+        EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload *)device, &cborData, &cborSize));
+        EXPECT_EQ(OC_STACK_OK, OCParsePayload(&parsedDevice, PAYLOAD_TYPE_DEVICE,
+                                              cborData, cborSize));
+        OICFree(cborData);
+        EXPECT_STREQ(device->dataModelVersions->value,
+                     ((OCDevicePayload *)parsedDevice)->dataModelVersions->value);
+        EXPECT_STREQ(device->dataModelVersions->next->value,
+                     ((OCDevicePayload *)parsedDevice)->dataModelVersions->next->value);
+        OCPayloadDestroy((OCPayload *)device);
+        OC::MessageContainer mc2;
+        mc2.setPayload(parsedDevice);
+        EXPECT_EQ(1u, mc2.representations().size());
+        const OC::OCRepresentation r2 = mc2.representations()[0];
+        EXPECT_STREQ("res.1.1.0", r2.getDataModelVersions()[0].c_str());
+        EXPECT_STREQ("sh.1.1.0", r2.getDataModelVersions()[1].c_str());
 
         OCPayloadDestroy(parsedDevice);
     }
@@ -137,7 +170,7 @@ namespace OCRepresentationEncodingTest
         EXPECT_STREQ(time1, platform->info.systemTime);
         EXPECT_STREQ(OC_RSRVD_INTERFACE_DEFAULT, platform->interfaces->value);
         EXPECT_STREQ(OC_RSRVD_INTERFACE_READ, platform->interfaces->next->value);
-        EXPECT_STREQ(OC_RSRVD_RESOURCE_TYPE_PLATFORM, platform->rt);
+        EXPECT_STREQ(OC_RSRVD_RESOURCE_TYPE_PLATFORM, platform->rt->value);
 
         uint8_t* cborData;
         size_t cborSize;
@@ -161,7 +194,7 @@ namespace OCRepresentationEncodingTest
         EXPECT_STREQ(platform->info.supportUrl, platform->info.supportUrl);
         EXPECT_STREQ(platform->info.systemTime, platform2->info.systemTime);
         EXPECT_STREQ(platform->interfaces->value, platform2->interfaces->value);
-        EXPECT_STREQ(platform->rt, platform2->rt);
+        EXPECT_STREQ(platform->rt->value, platform2->rt->value);
 
         OCPayloadDestroy((OCPayload*)platform);
 
index 3b9e711..ca6a9f1 100644 (file)
@@ -37,6 +37,12 @@ namespace OCResourceResponseTest
         int setCode = 200;
         EXPECT_NO_THROW(response.setErrorCode(setCode));
         EXPECT_EQ(setCode, response.getErrorCode());
+        setCode = 500;
+        EXPECT_NO_THROW(response.setErrorCode(setCode));
+        EXPECT_EQ(setCode, response.getErrorCode());
+        setCode = 400;
+        EXPECT_NO_THROW(response.setErrorCode(setCode));
+        EXPECT_EQ(setCode, response.getErrorCode());
     }
 
     TEST(NewResourceUriTest, SetGetNewResourceUriValidUri)
diff --git a/run.bat b/run.bat
new file mode 100644 (file)
index 0000000..5a97d6f
--- /dev/null
+++ b/run.bat
@@ -0,0 +1,130 @@
+@echo off
+REM Helper script to build and run IoTivity on Windows
+SETLOCAL ENABLEDELAYEDEXPANSION
+
+if [%1]==[] goto USAGE
+
+set IOTIVITY_DIR=%~dp0
+set HOME=%USERPROFILE%
+
+IF "%1" == "msys" (
+  set BUILD_MSYS="YES"
+  SHIFT
+) ELSE (
+  set BUILD_MSYS=
+)
+
+set CURRENT_ARG=%1
+set SECOND_ARG=%2
+set DEBUG=
+
+if "!SECOND_ARG!"=="debug" (
+  set DEBUG="%ProgramFiles(x86)%\Windows Kits\10\Debuggers\x64\cdb.exe" -2 -c "g" 
+)
+
+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
+  set PATH=!PATH!;!BUILD_DIR!;
+) ELSE (
+  set BUILD_DIR=out\msys_nt\x86_64\debug
+  set PATH=!PATH!;!BUILD_DIR!;C:\msys64\mingw64\bin
+)
+
+REM *** BUILD OPTIONS ***
+set TARGET_OS=windows
+set TARGET_ARCH=amd64
+set SECURED=1
+set TEST=1
+set LOGGING=OFF
+set WITH_RD=1
+REM *** BUILD OPTIONS ***
+
+if "!CURRENT_ARG!"=="server" (
+  %DEBUG% %BUILD_DIR%\resource\examples\simpleserver.exe
+) else if "!CURRENT_ARG!"=="client" (
+  %DEBUG% %BUILD_DIR%\resource\examples\simpleclient.exe
+) else if "!CURRENT_ARG!"=="mediaclient" (
+  %DEBUG% %BUILD_DIR%\debug\resource\examples\mediaclient.exe
+) else if "!CURRENT_ARG!"=="mediaserver" (
+  %DEBUG% %BUILD_DIR%\resource\examples\mediaserver.exe
+) else if "!CURRENT_ARG!"=="winuiclient" (
+  %DEBUG% %BUILD_DIR%\resource\examples\winuiclient.exe
+) else if "!CURRENT_ARG!"=="occlient" (
+  %DEBUG% %BUILD_DIR%\resource\csdk\stack\samples\linux\SimpleClientServer\occlientbasicops.exe -u 0 -t 3 -c 1
+) else if "!CURRENT_ARG!"=="ocserver" (
+  %DEBUG% %BUILD_DIR%\resource\csdk\stack\samples\linux\SimpleClientServer\ocserverbasicops.exe
+) else if "!CURRENT_ARG!"=="test" (
+  %DEBUG% %BUILD_DIR%\resource\csdk\connectivity\test\catests.exe
+  %DEBUG% %BUILD_DIR%\resource\csdk\stack\test\stacktests.exe
+  %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
+) 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   LOGGING=%LOGGING%
+  echo   WITH_RD=%WITH_RD%
+  CL.exe | findstr "Compiler Verison"
+  echo.scons VERBOSE=1 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%
+  scons VERBOSE=1 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%
+) else if "!CURRENT_ARG!"=="clean" (
+  scons VERBOSE=1 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% -c clean
+  rd /s /q out
+  del .sconsign.dblite
+) else if "!CURRENT_ARG!"=="cleangtest" (
+  rd /s /q extlibs\gtest\gtest-1.7.0
+  del extlibs\gtest\gtest-1.7.0.zip
+) else (
+    echo %0 - Script requires a valid argument!
+    goto :EOF
+)
+
+echo Done!
+
+goto EOF
+
+:USAGE
+echo %0 - Helper to build/test iotivity.  Requires an argument.
+echo Installation: Drop this into your iotivity root directory to use it.
+echo.
+echo. Usage examples:
+echo   Launch SimpleClient with debugger:
+echo      %0 client debug
+echo.
+echo   Launch SimpleServer:
+echo      %0 server
+echo.
+echo   Launch WinUIClient built in msys:
+echo      %0 msys winuiclient
+echo.
+echo   Build:
+echo      %0 build
+echo.
+echo   Run all tests:
+echo      %0 test
+echo.
+echo   Clean:
+echo      %0 clean
+
+:EOF
index 832cc76..1b9e7f3 100644 (file)
@@ -244,7 +244,7 @@ Below is an example:
        # Update the new environment, usually include add header file paths,
        # library path, libs to link and other compiler flags. This part is
        # optional.
-       new_env.AppeneUnique(xxx = [ .... ])
+       new_env.AppendUnique(xxx = [ .... ])
 
        # Specify the target(application, library, object or others) to build
        ts = new_env.Program('progam_name', [source_list])
index da5062e..114be6e 100755 (executable)
@@ -26,7 +26,7 @@ Import('env')
 
 target_os = env.get('TARGET_OS')
 
-if target_os not in ['arduino','darwin', 'ios']:
+if target_os not in ['arduino','darwin', 'ios', 'windows']:
     # Build things manager project
     SConscript('things-manager/SConscript')
 
@@ -47,9 +47,9 @@ if target_os not in ['arduino','darwin', 'ios']:
     if target_os in ['linux'] and env.get('SIMULATOR', False):
         SConscript('simulator/SConscript')
 
-    # Build resource directory project
-    if env.get('WITH_RD') == '1':
-        SConscript('resource-directory/SConscript')
+# Build resource directory project
+if env.get('WITH_RD') == '1':
+    SConscript('resource-directory/SConscript')
 
 # Build EasySetup module
 if target_os in ['arduino', 'android', 'linux','tizen']:
index 0c4ea68..53d2cfb 100644 (file)
@@ -68,7 +68,7 @@ if enrollee_env.get('SECURED') == '1':
                enrollee_env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal',
                enrollee_env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/oxm'])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
        enrollee_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
 
 ######################################################################
index 734f051..cad7dd2 100644 (file)
@@ -69,7 +69,7 @@ mediator_csdk_test_env.AppendUnique(
                 '../../../inc',
         ])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
         mediator_csdk_test_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
         if target_os != 'android':
                 mediator_csdk_test_env.AppendUnique(CXXFLAGS = ['-pthread'])
@@ -100,4 +100,4 @@ if env.get('TEST') == '1':
     target_os = env.get('TARGET_OS')
     if target_os == 'linux':
         from tools.scons.RunTest import *
-        run_test(mediator_csdk_test_env, '', 'service/easy-setup/mediator/csdk/unittests/mediator_csdk_test')
\ No newline at end of file
+        run_test(mediator_csdk_test_env, '', 'service/easy-setup/mediator/csdk/unittests/mediator_csdk_test')
index 6c0c101..f7cd0d9 100644 (file)
@@ -59,7 +59,7 @@ target_os = env.get('TARGET_OS')
 ######################################################################
 easy_setup_env.AppendUnique(CPPPATH = ['inc', 'src', '../../inc'])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
     easy_setup_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
 
 if target_os in ['linux']:
index 74d2ac3..b14b2c4 100644 (file)
@@ -39,7 +39,7 @@ LOCAL_C_INCLUDES := $(LOCAL_PATH) \
                                        $(LOCAL_PATH)/../../../../../../resource/include \
                                        $(LOCAL_PATH)/../../../../../../resource/c_common \
                                        $(LOCAL_PATH)/../../../../../../resource/oc_logger/include \
-                                       $(LOCAL_PATH)/../../../../../../resource/csdk/ocmalloc/include \
+                                       $(LOCAL_PATH)/../../../../../../resource/c_common/oic_malloc/include \
                                        $(LOCAL_PATH)/../../../../../../resource/csdk/connectivity/api \
                                        $(LOCAL_PATH)/../../../../../../resource/csdk/stack/include \
                                        $(LOCAL_PATH)/../../../../../../resource/csdk/logger/include \
index 099eddb..ca7bfad 100644 (file)
@@ -69,7 +69,7 @@ mediator_rich_test_env.AppendUnique(
                 '../../../inc',
         ])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
         mediator_rich_test_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
         if target_os != 'android':
                 mediator_rich_test_env.AppendUnique(CXXFLAGS = ['-pthread'])
index 0cd8288..cfb1695 100644 (file)
@@ -29,7 +29,7 @@ print "Inside the Config SConscript"
 # Map of host os and allowed target os (host: allowed target os)
 host_target_map = {
         'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
-        'windows': ['windows', 'winrt', 'android', 'arduino', 'tizen'],
+        'windows': ['windows', 'android', 'arduino', 'tizen'],
         'darwin': ['darwin', 'ios', 'android', 'arduino'],
         }
 
@@ -38,7 +38,6 @@ os_arch_map = {
         'linux': ['x86', 'x86_64', 'arm', 'arm64'],
         'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
         'windows': ['x86', 'amd64', 'arm'],
-        'winrt': ['arm'],
         'darwin': ['i386', 'x86_64'],
         'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
         'arduino': ['avr', 'arm'],
index 7082662..e9333a7 100644 (file)
@@ -8,7 +8,7 @@ import platform
 # Map of host os and allowed target os (host: allowed target os)
 host_target_map = {
                'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
-               'windows': ['windows', 'winrt', 'android', 'arduino'],
+               'windows': ['windows', 'android', 'arduino'],
                'darwin': ['darwin', 'ios', 'android', 'arduino'],
                }
 
@@ -18,7 +18,6 @@ os_arch_map = {
                'tizen': ['x86', 'x86_64', 'arm', 'arm64'],
                'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
                'windows': ['x86', 'amd64', 'arm'],
-               'winrt': ['arm'],
                'darwin': ['i386', 'x86_64'],
                'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
                'arduino': ['avr', 'arm'],
index 3b49c9a..272db45 100644 (file)
@@ -2,8 +2,8 @@
 %define ROOTDIR  %{_builddir}/%{name}-%{version}
 
 Name: com-oic-es-sample
-Version:    0.1
-Release:    1
+Version:    1.1.1
+Release:    0
 Summary: Tizen adapter interfacesample application
 URL: http://slp-source.sec.samsung.net
 Source: %{name}-%{version}.tar.gz
index cb6a70f..6dd3a0c 100644 (file)
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 592bc1b..2d47964 100644 (file)
@@ -8,38 +8,38 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
                         },\r
                         {\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
-                            "href": "/oic/res/types/d",\r
+                            "href": "/oic/ad",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.ad"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
-                            "href": "/oic/ad",\r
+                            "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
-                            "href": "/oic/sec/acl",\r
+                            "href": "/oic/res/types/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        } ,\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
@@ -83,6 +83,6 @@
         "deviceuuid": "61646d69-6e44-6576-6963-655575696430",\r
         "devowneruuid": "61646d69-6e44-6576-6963-655575696430",\r
         "rowneruuid": "61646d69-6e44-6576-6963-655575696430",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     }\r
 }\r
index 4d60705..06ed5c4 100644 (file)
@@ -31,7 +31,7 @@ mediator_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 mediator_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 
 mediator_env.PrependUnique(CPPPATH = [
-                       env.get('SRC_DIR') + '/resource/csdk/ocmalloc/include',         
+                       env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',
                        env.get('SRC_DIR') + '/resource/csdk/connectivity/common/inc',
                        env.get('SRC_DIR') + '/resource/csdk/connectivity/api',
                        env.get('SRC_DIR') + '/resource/csdk/stack/include',
index cc66800..eb2ab43 100644 (file)
@@ -40,13 +40,13 @@ if env.get('LOGGING'):
 
 env.AppendUnique(CPPDEFINES = ['CPP_MEDIATOR'])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
     mediator_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
 
 mediator_env.PrependUnique(CPPPATH = [
             env.get('SRC_DIR') + '/resource/include',
             env.get('SRC_DIR') + '/resource/oc_logger/include',
-                       env.get('SRC_DIR') + '/resource/csdk/ocmalloc/include',
+                       env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',
                        env.get('SRC_DIR') + '/resource/csdk/stack/include',
                        env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include',
                        env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal',
index 62be9f2..770cede 100644 (file)
@@ -83,12 +83,12 @@ if int(containerJavaSupport):
         print ''
 
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
     resource_container_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
     if target_os != 'android':
         resource_container_env.AppendUnique(CXXFLAGS = ['-pthread'])
 
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
     resource_container_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
 
 if target_os == 'android':
index f56bc07..6bf73e1 100644 (file)
@@ -24,7 +24,8 @@
 #include "BMISensor.h"
 
 #include <iostream>
-#include <stdlib.h>
+#include <cmath>
+#include <cstdlib>
 #include "SysTimer.h"
 
 #ifdef __ANDROID__
@@ -90,7 +91,7 @@ BMIResult BMISensor::makeBMI(void)
         dWeight = std::stod(m_weight);
         dHeight = std::stod(m_height);
 
-        timediffsecond = abs(difftime(m_timepstampW, m_timepstampH));
+        timediffsecond = std::abs(difftime(m_timepstampW, m_timepstampH));
 
         // check if time difference between weight data and height data is valid
         if (timediffsecond > DIFFTIME)
index e9e79de..2a527b5 100644 (file)
@@ -35,12 +35,14 @@ void BMISensorResource::handleSetAttributesRequest(
     const RCSResourceAttributes &value,
     const std::map< std::string, std::string > &queryParams)
 {
+    (void)queryParams;
     BundleResource::setAttributes(value);
 }
 
 RCSResourceAttributes BMISensorResource::handleGetAttributesRequest(const
         std::map< std::string, std::string > &queryParams)
 {
+    (void)queryParams;
     return BundleResource::getAttributes();
 }
 
index 20516e4..81cf79d 100644 (file)
@@ -16,9 +16,9 @@ linux_sample_env.AppendUnique(CPPPATH = ['include'])
 linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
 linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
 linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-linux_sample_env.AppendUnique(LIBS = ['libcoap'])
-linux_sample_env.AppendUnique(LIBS = ['libconnectivity_abstraction'])
-linux_sample_env.AppendUnique(LIBS = ['liboc_logger'])
+linux_sample_env.AppendUnique(LIBS = ['coap'])
+linux_sample_env.AppendUnique(LIBS = ['connectivity_abstraction'])
+linux_sample_env.AppendUnique(LIBS = ['oc_logger'])
 linux_sample_env.AppendUnique(LIBS = ['octbstack'])
 linux_sample_env.AppendUnique(LIBS = ['oc'])
 linux_sample_env.AppendUnique(LIBS = ['pthread'])
index 05980ab..2f6f857 100644 (file)
@@ -38,12 +38,14 @@ void DiscomfortIndexSensorResource::handleSetAttributesRequest(
     const RCSResourceAttributes &value,
     const std::map< std::string, std::string > &queryParams)
 {
+    (void)queryParams;
     BundleResource::setAttributes(value);
 }
 
 RCSResourceAttributes DiscomfortIndexSensorResource::handleGetAttributesRequest(
     const std::map< std::string, std::string > &queryParams)
 {
+    (void)queryParams;
     return BundleResource::getAttributes();
 }
 
index ed94470..a72a7b4 100644 (file)
 #ifndef CONFIGURATION_H_
 #define CONFIGURATION_H_
 
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_STRING_H
 #include <string.h>
+#endif
 #include <iostream>
 #include <fstream>
 #include <string>
index eb4849a..48825cc 100644 (file)
@@ -103,12 +103,14 @@ class TestBundleResource: public BundleResource
         virtual void handleSetAttributesRequest(const RCSResourceAttributes &attr,
                                                 const std::map< std::string, std::string > &queryParams)
         {
+            (void)queryParams;
             BundleResource::setAttributes(attr);
         }
 
         virtual RCSResourceAttributes handleGetAttributesRequest(const
                 std::map< std::string, std::string > &queryParams)
         {
+            (void)queryParams;
             return BundleResource::getAttributes();
         }
 };
@@ -126,12 +128,14 @@ class TestBundleResourceWithAttrs: public BundleResource
         virtual void handleSetAttributesRequest(const RCSResourceAttributes &attr,
                                                 const std::map< std::string, std::string > &queryParams)
         {
+            (void)queryParams;
             BundleResource::setAttributes(attr);
         }
 
         virtual RCSResourceAttributes handleGetAttributesRequest(const
                 std::map< std::string, std::string > &queryParams)
         {
+            (void)queryParams;
             return BundleResource::getAttributes();
         }
 };
@@ -148,12 +152,14 @@ class TestSoftSensorResource: public SoftSensorResource
         virtual void handleSetAttributesRequest(const RCSResourceAttributes &attr,
                                                 const std::map< std::string, std::string > &queryParams)
         {
+            (void)queryParams;
             BundleResource::setAttributes(attr);
         }
 
         virtual RCSResourceAttributes handleGetAttributesRequest(const
                  std::map< std::string, std::string > &queryParams)
         {
+            (void)queryParams;
             return BundleResource::getAttributes();
         }
 
index ecc5306..e79f360 100644 (file)
@@ -106,7 +106,7 @@ if int(containerJavaSupport):
     except KeyError:
         print ''
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
     container_gtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
     if target_os != 'android':
         container_gtest_env.AppendUnique(CXXFLAGS = ['-pthread'])
@@ -144,7 +144,7 @@ if int(containerJavaSupport):
 test_bundle_env = container_gtest_env.Clone()
 test_bundle_env.AppendUnique(CCFLAGS = ['-fPIC'])
 
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
     test_bundle_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
 
 TEST_BUNDLE_DIR = 'TestBundle/'
@@ -181,4 +181,4 @@ if env.get('TEST') == '1':
         from tools.scons.RunTest import *
         run_test(container_gtest_env,
             '',
-            'service/resource-container/unittests/container_test')
\ No newline at end of file
+            'service/resource-container/unittests/container_test')
index 4f39b21..6657014 100644 (file)
@@ -55,6 +55,7 @@ class TestBundleResource : public BundleResource
         RCSResourceAttributes handleGetAttributesRequest(
             const std::map< std::string, std::string > &queryParams)
         {
+            (void)queryParams;
             return BundleResource::getAttributes();
         }
 
@@ -62,6 +63,7 @@ class TestBundleResource : public BundleResource
             const RCSResourceAttributes &value,
             const std::map< std::string, std::string > &queryParams)
         {
+            (void)queryParams;
             BundleResource::setAttributes(value);
         }
 };
index b6ef553..b7e47f0 100755 (executable)
 ##
 
 Import('env')
+rd_env = env.Clone()
 
-if env.get('RELEASE'):
-    env.AppendUnique(CCFLAGS = ['-Os'])
-    env.AppendUnique(CPPDEFINES = ['NDEBUG'])
-else:
-    env.AppendUnique(CCFLAGS = ['-g'])
-
-if env.get('LOGGING'):
-    env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
-
-lib_env = env.Clone()
-SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
-rd_env = lib_env.Clone()
+if rd_env.get('LOGGING'):
+    rd_env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
 
 target_os = env.get('TARGET_OS')
+src_dir = env.get('SRC_DIR')
+
 ######################################################################
 # Build flags
 ######################################################################
 rd_env.AppendUnique(CPPPATH = ['include'])
 rd_env.AppendUnique(CPPPATH = ['src/internal'])
-rd_env.AppendUnique(CPPPATH = ['../../resource/csdk/logger/include'])
-rd_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'libcoap'])
+rd_env.AppendUnique(CPPPATH = ['../../resource/csdk/stack/include'])
+rd_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap'])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
     rd_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra'])
 
 if target_os == 'linux':
@@ -64,7 +57,7 @@ if target_os == 'android':
 ######################################################################
 RD_SRC_DIR = 'src/'
 rd_src = [
-        RD_SRC_DIR + '/internal/rd_storage.c',
+        RD_SRC_DIR + 'internal/rd_storage.c',
         RD_SRC_DIR + 'rd_server.c',
         RD_SRC_DIR + 'rd_client.c',
          ]
@@ -74,12 +67,13 @@ if target_os in ['tizen'] :
 else :
     rdsdk = rd_env.StaticLibrary('resource_directory', rd_src)
 
-rd_env.InstallTarget(rdsdk, 'libresource_directory')
-rd_env.UserInstallTargetLib(rdsdk, 'libresource_directory')
-rd_env.UserInstallTargetHeader('/include/rd_client.h', 'service/resource-directory', 'rd_client.h')
-rd_env.UserInstallTargetHeader('/include/rd_server.h', 'service/resource-directory', 'rd_server.h')
+rd_env.InstallTarget(rdsdk, 'resource_directory')
+rd_env.UserInstallTargetLib(rdsdk, 'resource_directory')
+rd_env.UserInstallTargetHeader('include/rd_client.h', 'service/resource-directory', 'rd_client.h')
+rd_env.UserInstallTargetHeader('include/rd_server.h', 'service/resource-directory', 'rd_server.h')
 
 ######################################################################
 # Samples for the resource directory
 ######################################################################
-SConscript('samples/SConscript')
+if target_os not in ['windows']:
+    SConscript('samples/SConscript')
index c4d2128..8229a61 100644 (file)
@@ -29,12 +29,14 @@ SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
 
 rd_sample_app_env = lib_env.Clone()
 
+target_os = env.get('TARGET_OS')
 ######################################################################
 # Build flags
 ######################################################################
 rd_sample_app_env.AppendUnique(CPPPATH = ['../include'])
 
-rd_sample_app_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra', '-std=c++0x'])
+if target_os not in ['windows']:
+    rd_sample_app_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra', '-std=c++0x'])
 rd_sample_app_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 rd_sample_app_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
 rd_sample_app_env.PrependUnique(LIBS = ['resource_directory', 'oc', 'octbstack'])
index cad3ef3..e9b72ff 100644 (file)
@@ -20,7 +20,9 @@
 #include "rd_server.h"
 
 #include <signal.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 
 int g_quitFlag = 0;
 
index 2f6c922..c782560 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 #include "rd_storage.h"
 
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
 #include <string.h>
 
 #include "payload_logging.h"
 
 #define TAG  PCF("RDStorage")
 
-pthread_mutex_t storageMutex = PTHREAD_MUTEX_INITIALIZER;
-// This variable holds the published resources on the RD.
+// Mutex implementation macros
+#if defined(HAVE_PTHREAD_H)
+
+#include <pthread.h>
+pthread_mutex_t storageMutex;
+#define MUTEX_LOCK(ARG_NAME)    { pthread_mutex_lock(ARG_NAME); }
+#define MUTEX_UNLOCK(ARG_NAME)  { pthread_mutex_unlock(ARG_NAME); }
+
+#elif defined(HAVE_WINDOWS_H)
+
+#include <windows.h>
+CRITICAL_SECTION storageMutex;
+#define MUTEX_LOCK(ARG_NAME)   { EnterCriticalSection(ARG_NAME); }
+#define MUTEX_UNLOCK(ARG_NAME) { LeaveCriticalSection(ARG_NAME); }
+
+#else
+
+ERROR Need mutex implementation for this platform
+#define MUTEX_LOCK(ARG_NAME)   {  }
+#define MUTEX_UNLOCK(ARG_NAME) {  }
+
+#endif
+
+
 static OCRDStorePublishResources *g_rdStorage = NULL;
 
 static void printStoragedResources(OCRDStorePublishResources *payload)
@@ -109,7 +136,7 @@ OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *pay
     resources->publishedResource = storeResource;
     resources->devAddr = *address;
 
-    pthread_mutex_lock(&storageMutex);
+    MUTEX_LOCK(&storageMutex);
     if (g_rdStorage)
     {
         OCRDStorePublishResources *temp = g_rdStorage;
@@ -123,7 +150,7 @@ OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *pay
     {
         g_rdStorage = resources;
     }
-    pthread_mutex_unlock(&storageMutex);
+    MUTEX_UNLOCK(&storageMutex);
 
     printStoragedResources(g_rdStorage);
     return OC_STACK_OK;
index a50bf2c..d444431 100644 (file)
@@ -24,6 +24,7 @@
 #include "oic_string.h"
 #include "oic_malloc.h"
 #include "payload_logging.h"
+#include "platform_features.h"
 
 #include "rdpayload.h"
 #include "ocpayload.h"
@@ -62,9 +63,9 @@ static OCStackResult sendRequest(OCMethod method, char *uri, OCDevAddr *addr,
     return result;
 }
 
-static OCStackApplicationResult handlePublishCB(__attribute__((unused))void *ctx,
-        __attribute__((unused)) OCDoHandle handle,
-        __attribute__((unused)) OCClientResponse *clientResponse)
+static OCStackApplicationResult handlePublishCB(OC_ANNOTATE_UNUSED void *ctx,
+        OC_ANNOTATE_UNUSED OCDoHandle handle,
+        OC_ANNOTATE_UNUSED OCClientResponse *clientResponse)
 {
     OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;
     OIC_LOG(DEBUG, TAG, "Successfully published resources.");
@@ -99,7 +100,7 @@ static void retreiveRDDetails(OCClientResponse *clientResponse, OCRDBiasFactorCB
 }
 
 static OCStackApplicationResult handleDiscoverCB(void *ctx,
-        __attribute__((unused)) OCDoHandle handle, OCClientResponse *clientResponse)
+        OC_ANNOTATE_UNUSED OCDoHandle handle, OCClientResponse *clientResponse)
 {
     OIC_LOG(DEBUG, TAG, "Found Resource Directory");
     OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;
index e97fedf..11252d2 100644 (file)
@@ -123,7 +123,7 @@ static OCEntityHandlerResult handlePublishRequest(const OCEntityHandlerRequest *
  * will handle REST request (GET/PUT/POST/DEL) for them.
  */
 static OCEntityHandlerResult rdEntityHandler(OCEntityHandlerFlag flag,
-        OCEntityHandlerRequest *ehRequest, __attribute__((unused)) void *callbackParameter)
+        OCEntityHandlerRequest *ehRequest, OC_ANNOTATE_UNUSED void *callbackParameter)
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
 
index d82b5f5..30d1ad7 100644 (file)
@@ -61,7 +61,7 @@ resourceClient_env.AppendUnique(CPPPATH = [
 
 resourceClient_env.PrependUnique(LIBS = ['oc', 'rcs_common', 'octbstack','oc_logger'])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
     resourceClient_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
 if target_os == 'linux':
    resourceClient_env.AppendUnique(LIBS = ['pthread'])
@@ -93,8 +93,8 @@ client_src = [
 ResourceClientsdk_static = resourceClient_env.StaticLibrary('rcs_client', client_src)
 ResourceClientsdk_shared = resourceClient_env.SharedLibrary('rcs_client', client_src)
 
-resourceClient_env.InstallTarget([ResourceClientsdk_static,ResourceClientsdk_shared], 'librcs_client')
-resourceClient_env.UserInstallTargetLib([ResourceClientsdk_static,ResourceClientsdk_shared], 'librcs_client')
+resourceClient_env.InstallTarget([ResourceClientsdk_static,ResourceClientsdk_shared], 'rcs_client')
+resourceClient_env.UserInstallTargetLib([ResourceClientsdk_static,ResourceClientsdk_shared], 'rcs_client')
 resourceClient_env.UserInstallTargetHeader('include/RCSAddress.h', 'service/resource-encapsulation', 'RCSAddress.h')
 resourceClient_env.UserInstallTargetHeader('include/RCSDiscoveryManager.h', 'service/resource-encapsulation', 'RCSDiscoveryManager.h')
 resourceClient_env.UserInstallTargetHeader('include/RCSRemoteResourceObject.h', 'service/resource-encapsulation', 'RCSRemoteResourceObject.h')
@@ -119,4 +119,4 @@ if target_os == 'linux':
     SConscript('src/resourceBroker/unittest/SConscript')
 
 if target_os == 'android':
-    SConscript('android/SConscript')
\ No newline at end of file
+    SConscript('android/SConscript')
index 9de47b8..59c0c32 100644 (file)
Binary files a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.dat and b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.dat differ
index 5052bd1..e4c9681 100644 (file)
@@ -8,38 +8,32 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
                         },\r
                         {\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/ad",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.ad"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        } ,\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
@@ -83,7 +77,7 @@
         "deviceuuid": "32323232-3232-3232-3232-323232323232",\r
         "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
         "rowneruuid": "32323232-3232-3232-3232-323232323232",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     },\r
     "cred": {\r
         "creds": [\r
index 31e1814..742069a 100644 (file)
Binary files a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.dat and b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.dat differ
index 0e1bf23..6094a95 100644 (file)
@@ -8,38 +8,32 @@
                         {\r
                             "href": "/oic/res",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.res"],\r
+                            "if": ["oic.if.ll"]\r
                         },\r
                         {\r
                             "href": "/oic/d",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.d"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/p",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        },\r
-                        {\r
-                            "href": "/oic/res/types/d",\r
-                            "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.p"],\r
+                            "if": ["oic.if.baseline", "oic.if.r"]\r
                         },\r
                         {\r
                             "href": "/oic/ad",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.wk.ad"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/oic/sec/acl",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.acl"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/oic/sec/doxm",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
-                        } ,\r
+                            "rt": ["oic.r.doxm"],\r
+                            "if": ["oic.if.baseline"]\r
+                        },\r
                         {\r
                             "href": "/oic/sec/pstat",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.r.pstat"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 2\r
                         {\r
                             "href": "/a/light",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.core"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/a/light0",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.core"],\r
+                            "if": ["oic.if.baseline"]\r
                         },\r
                         {\r
                             "href": "/a/light1",\r
                             "rel": "",\r
-                            "rt": "",\r
-                            "if": ""\r
+                            "rt": ["oic.core"],\r
+                            "if": ["oic.if.baseline"]\r
                         }\r
                     ],\r
                     "permission": 6\r
         "deviceuuid": "31313131-3131-3131-3131-313131313131",\r
         "devowneruuid": "32323232-3232-3232-3232-323232323232",\r
         "rowneruuid": "31313131-3131-3131-3131-313131313131",\r
-        "dpc": false\r
+        "x.com.samsung.dpc": false\r
     },\r
     "cred": {\r
         "creds": [\r
index 1ced6af..b2f7bd9 100644 (file)
@@ -30,6 +30,8 @@
 
 #include <octypes.h>
 
+#include "boost/config.hpp"
+
 namespace OIC
 {
     namespace Service
@@ -69,13 +71,13 @@ namespace OIC
              */
             explicit RCSException(std::string &&what);
 
-            virtual ~RCSException() noexcept;
+            virtual ~RCSException() BOOST_NOEXCEPT;
 
             /**
              * Returns the exception description.
              *
              */
-            virtual const char *what() const noexcept;
+            virtual const char *what() const BOOST_NOEXCEPT;
 
         private:
             /**
index 2901d78..6fcff21 100644 (file)
@@ -113,7 +113,7 @@ namespace OIC
             class KeyValueVisitorHelper: public boost::static_visitor< >
             {
             public:
-                KeyValueVisitorHelper(VISITOR& visitor) noexcept :
+                KeyValueVisitorHelper(VISITOR& visitor) BOOST_NOEXCEPT :
                         m_visitor( visitor )
                 {
                 }
@@ -186,7 +186,7 @@ namespace OIC
                  *
                  * @see getBaseTypeId
                  */
-                TypeId getId() const noexcept;
+                TypeId getId() const BOOST_NOEXCEPT;
 
                 /**
                  * Returns the type identifier of a base type of sequence.
@@ -198,7 +198,7 @@ namespace OIC
                  * @see getDepth
                  * @see getId
                  */
-                static TypeId getBaseTypeId(const Type& t) noexcept;
+                static TypeId getBaseTypeId(const Type& t) BOOST_NOEXCEPT;
 
                 /**
                  * Returns the depth of a type.
@@ -207,7 +207,7 @@ namespace OIC
                  *
                  * @see getBaseTypeId
                  */
-                static size_t getDepth(const Type& t) noexcept;
+                static size_t getDepth(const Type& t) BOOST_NOEXCEPT;
 
                 /**
                  * Factory method to create Type instance from T.
@@ -219,7 +219,7 @@ namespace OIC
                  * @see is_supported_type
                  */
                 template < typename T >
-                constexpr static Type typeOf(const T&) noexcept
+                constexpr static Type typeOf(const T&) BOOST_NOEXCEPT
                 {
                     return Type{ IndexOfType< T >::value };
                 }
@@ -234,17 +234,17 @@ namespace OIC
                  * @see is_supported_type
                  */
                 template < typename T >
-                constexpr static Type typeOf() noexcept
+                constexpr static Type typeOf() BOOST_NOEXCEPT
                 {
                     return Type{ IndexOfType< T >::value };
                 }
 
                 //! @cond
-                friend bool operator==(const Type&, const Type&) noexcept;
+                friend bool operator==(const Type&, const Type&) BOOST_NOEXCEPT;
                 //! @endcond
 
             private:
-                constexpr explicit Type(int which) noexcept :
+                constexpr explicit Type(int which) BOOST_NOEXCEPT :
                     m_which{ which }
                 {
                 }
@@ -299,7 +299,7 @@ namespace OIC
 
                 Value();
                 Value(const Value&);
-                Value(Value&&) noexcept;
+                Value(Value&&) BOOST_NOEXCEPT;
 
                 /**
                  * Constructs a Value if T is a supported type.<br/>
@@ -368,7 +368,7 @@ namespace OIC
                 /**
                  * Exchanges the content of the object by the content of the parameter.
                  */
-                void swap(Value&) noexcept;
+                void swap(Value&) BOOST_NOEXCEPT;
 
                 //! @cond
                 friend class RCSResourceAttributes;
@@ -420,32 +420,32 @@ namespace OIC
             /**
              * Returns an {@link iterator} referring to the first element.
              */
-            iterator begin() noexcept;
+            iterator begin() BOOST_NOEXCEPT;
 
             /**
              * Returns an {@link iterator} referring to the <i>past-the-end element</i>.
              */
-            iterator end() noexcept;
+            iterator end() BOOST_NOEXCEPT;
 
             /**
              * @copydoc cbegin()
              */
-            const_iterator begin() const noexcept;
+            const_iterator begin() const BOOST_NOEXCEPT;
 
             /**
              * @copydoc cend()
              */
-            const_iterator end() const noexcept;
+            const_iterator end() const BOOST_NOEXCEPT;
 
             /**
              * Returns a const_iterator referring to the first element.
              */
-            const_iterator cbegin() const noexcept;
+            const_iterator cbegin() const BOOST_NOEXCEPT;
 
             /**
              * Returns a const_iterator referring to the <i>past-the-end element</i>.
              */
-            const_iterator cend() const noexcept;
+            const_iterator cend() const BOOST_NOEXCEPT;
 
             /**
              * Accesses a value.
@@ -519,7 +519,7 @@ namespace OIC
             /**
              * Removes all elements.
              */
-            void clear() noexcept;
+            void clear() BOOST_NOEXCEPT;
 
             /**
              * Removes a single element.
@@ -553,14 +553,14 @@ namespace OIC
              *
              * @see size
              */
-            bool empty() const noexcept;
+            bool empty() const BOOST_NOEXCEPT;
 
             /**
              * Returns the number of elements.
              *
              * @see empty
              */
-            size_t size() const noexcept;
+            size_t size() const BOOST_NOEXCEPT;
 
         private:
             template< typename VISITOR >
@@ -662,7 +662,7 @@ namespace OIC
          * @return true if the objects are equal, false otherwise.
          */
         bool operator==(const RCSResourceAttributes::Type&, const RCSResourceAttributes::Type&)
-                noexcept;
+                BOOST_NOEXCEPT;
 
         /**
          * @relates RCSResourceAttributes::Type
@@ -672,7 +672,7 @@ namespace OIC
          * @return true if the objects are not equal, false otherwise.
          */
         bool operator!=(const RCSResourceAttributes::Type&, const RCSResourceAttributes::Type&)
-                noexcept;
+                BOOST_NOEXCEPT;
 
         /**
          * @relates RCSResourceAttributes::Value
@@ -763,32 +763,32 @@ namespace OIC
             class KeyVisitor: public boost::static_visitor< const std::string& >
             {
             public:
-                result_type operator()(iterator*) const noexcept;
-                result_type operator()(const_iterator*) const noexcept;
+                result_type operator()(iterator*) const BOOST_NOEXCEPT;
+                result_type operator()(const_iterator*) const BOOST_NOEXCEPT;
             };
 
             class ValueVisitor: public boost::static_visitor< Value& >
             {
             public:
-                result_type operator()(iterator*) noexcept;
+                result_type operator()(iterator*) BOOST_NOEXCEPT;
                 result_type operator()(const_iterator*);
             };
 
             class ConstValueVisitor: public boost::static_visitor< const Value& >
             {
             public:
-                result_type operator()(iterator*) const noexcept;
-                result_type operator()(const_iterator*) const noexcept;
+                result_type operator()(iterator*) const BOOST_NOEXCEPT;
+                result_type operator()(const_iterator*) const BOOST_NOEXCEPT;
             };
 
         public:
-            const std::string& key() const noexcept;
-            const RCSResourceAttributes::Value& value() const noexcept;
+            const std::string& key() const BOOST_NOEXCEPT;
+            const RCSResourceAttributes::Value& value() const BOOST_NOEXCEPT;
             RCSResourceAttributes::Value& value();
 
         private:
             KeyValuePair(const KeyValuePair&) = default;
-            KeyValuePair(boost::variant< iterator*, const_iterator* >&&) noexcept;
+            KeyValuePair(boost::variant< iterator*, const_iterator* >&&) BOOST_NOEXCEPT;
 
             KeyValuePair& operator=(const KeyValuePair&) = default;
 
index 8a58b15..ff68863 100644 (file)
@@ -79,14 +79,36 @@ namespace OIC
          * in instead of overriding SetRequestHandler.
          * </p>
          */
+
         class RCSResourceObject
         {
         private:
-            class WeakGuard;
 
             typedef AtomicWrapper< std::thread::id > AtomicThreadId;
 
+        //! @cond
+        class WeakGuard
+        {
+        public:
+            WeakGuard(const RCSResourceObject&);
+            ~WeakGuard();
+
+            WeakGuard(const WeakGuard&) = delete;
+            WeakGuard(WeakGuard&&) = delete;
+
+            WeakGuard& operator=(const WeakGuard&) = delete;
+            WeakGuard& operator=(WeakGuard&&) = delete;
+
+            bool hasLocked() const;
+
+        private:
+            bool m_isOwningLock;
+            const RCSResourceObject& m_resourceObject;
+        };
+        //! @endcond
+
         public:
+
             /**
              * Represents the policy of auto-notify function.
              * In accord with this policy, observers are notified of attributes
@@ -328,7 +350,7 @@ namespace OIC
             template< typename T >
             T getAttribute(const std::string& key) const
             {
-                WeakGuard lock(*this);
+               RCSResourceObject::WeakGuard lock(*this);
                 return m_resourceAttributes.at(key).get< T >();
             }
 
@@ -668,26 +690,6 @@ namespace OIC
             std::function<void()> m_autoNotifyFunc;
         };
 
-        //! @cond
-        class RCSResourceObject::WeakGuard
-        {
-        public:
-            WeakGuard(const RCSResourceObject&);
-            ~WeakGuard();
-
-            WeakGuard(const WeakGuard&) = delete;
-            WeakGuard(WeakGuard&&) = delete;
-
-            WeakGuard& operator=(const WeakGuard&) = delete;
-            WeakGuard& operator=(WeakGuard&&) = delete;
-
-            bool hasLocked() const;
-
-        private:
-            bool m_isOwningLock;
-            const RCSResourceObject& m_resourceObject;
-        };
-        //! @endcond
     }
 }
 
index 06efb88..4c9cf74 100644 (file)
@@ -51,13 +51,13 @@ rcs_common_env.AppendUnique(CPPPATH = [
 
 rcs_common_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
     rcs_common_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
     if target_os != 'android':
         rcs_common_env.AppendUnique(CXXFLAGS = ['-pthread'])
         rcs_common_env.AppendUnique(LIBS = ['pthread'])
 
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
     rcs_common_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
 
 if target_os == 'android':
index 00012e6..b6be66f 100644 (file)
@@ -72,7 +72,7 @@ broker_test_env.AppendUnique(LIBS = ['rcs_common'])
 broker_test_env.AppendUnique(LIBS = [gtest])
 broker_test_env.AppendUnique(LIBS = [gtest_main])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
     broker_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
 
 if target_os == 'linux':
index 7a7d992..50b0f8f 100644 (file)
@@ -62,7 +62,7 @@ cache_test_env.PrependUnique(CPPPATH = [env.get('SRC_DIR')+'/extlibs/hippomocks-
 cache_test_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 cache_test_env.PrependUnique(LIBS = ['rcs_client', 'rcs_common', 'oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', gtest, gtest_main])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
     cache_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
 
 if target_os == 'linux':
@@ -82,4 +82,4 @@ if env.get('TEST') == '1':
                 from tools.scons.RunTest import *
                 run_test(cache_test_env,
                          'cache_test.memcheck',
-                         'service/resource-encapsulation/src/resourceCache/unittests/cache_test')
\ No newline at end of file
+                         'service/resource-encapsulation/src/resourceCache/unittests/cache_test')
index 563d1d6..111d91d 100644 (file)
@@ -50,12 +50,12 @@ server_builder_env.AppendUnique(CPPPATH = [env.get('SRC_DIR')+'/extlibs', 'inclu
 
 server_builder_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
     server_builder_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
     if target_os != 'android':
         server_builder_env.AppendUnique(CXXFLAGS = ['-pthread'])
 
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
     server_builder_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
 
 if target_os == 'android':
index 1a40150..f45ab77 100644 (file)
@@ -815,7 +815,7 @@ namespace OIC
                     m_resourceObject, m_resourceObject.m_resourceAttributes, m_autoNotifyPolicy);
         }
 
-        RCSResourceObject::WeakGuard::WeakGuard(
+      RCSResourceObject::WeakGuard::WeakGuard(
                 const RCSResourceObject& resourceObject) :
                 m_isOwningLock{ false },
                 m_resourceObject(resourceObject)
index 7af50f7..b86b795 100644 (file)
@@ -69,7 +69,7 @@ rcs_test_env.AppendUnique(
                 '../src/common/utils/include',
         ])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
         rcs_test_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
         if target_os != 'android':
                 rcs_test_env.AppendUnique(CXXFLAGS = ['-pthread'])
index 6e02574..fd9d622 100644 (file)
@@ -56,10 +56,10 @@ resourcehosting_env.PrependUnique(LIBS = [
        'libcoap'
        ])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
        resourcehosting_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
 
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
        resourcehosting_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
 
 if target_os == 'linux':
@@ -88,8 +88,8 @@ if target_os in ['tizen','android'] :
 else :
     resourcehostingsdk = resourcehosting_env.StaticLibrary('resource_hosting', resourcehosting_src)
 
-resourcehosting_env.InstallTarget(resourcehostingsdk, 'libresource_hosting')
-resourcehosting_env.UserInstallTargetLib(resourcehostingsdk, 'libresource_hosting')
+resourcehosting_env.InstallTarget(resourcehostingsdk, 'resource_hosting')
+resourcehosting_env.UserInstallTargetLib(resourcehostingsdk, 'resource_hosting')
 resourcehosting_env.UserInstallTargetHeader('include/Hosting.h',\
        'service/resource-hosting', 'Hosting.h')
 
index 4ff3df8..a800415 100755 (executable)
 #include "RCSRemoteResourceObject.h"
 #include "RCSResourceObject.h"
 
+#ifdef _MSC_VER
+#define OIC_HOSTING_LOG(level, fmt, ...) OIC_LOG_V((level), PCF("Hosting"), fmt, __VA_ARGS__)
+#else
 #define OIC_HOSTING_LOG(level, fmt, args...) OIC_LOG_V((level), PCF("Hosting"), fmt, ##args)
+#endif
 
 namespace OIC
 {
index 2b15b0a..5fa595b 100644 (file)
@@ -58,7 +58,7 @@ hosting_test_env.AppendUnique(LIBS = [
        'oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap',
        GTest_Main, GTest])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
     hosting_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
 
 if target_os == 'linux':
@@ -84,4 +84,4 @@ if env.get('TEST') == '1':
     target_os = env.get('TARGET_OS')
     if target_os == 'linux':
             from tools.scons.RunTest import *
-            run_test(hosting_test_env, '', 'service/resource-hosting/unittest/hosting_test')
\ No newline at end of file
+            run_test(hosting_test_env, '', 'service/resource-hosting/unittest/hosting_test')
index d351104..c0c4a27 100755 (executable)
@@ -60,10 +60,10 @@ scenemanager_env.PrependUnique(LIBS = [
     'rcs_common'
     ])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
     scenemanager_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
 
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
     scenemanager_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
 
 if target_os == 'linux':
index 25d65d8..ea9e48d 100755 (executable)
@@ -58,7 +58,7 @@ scene_test_env.AppendUnique(LIBS = [
     'oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap',
     GTest_Main, GTest])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
     scene_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
 
 if target_os == 'linux':
@@ -129,4 +129,4 @@ env.AppendTarget('remote_scene_action_test')
 #        from tools.scons.RunTest import *
 #        run_test(scene_test_env,
 #                 '',
-#                 'service/scene-manager/unittest/scene_test')
\ No newline at end of file
+#                 'service/scene-manager/unittest/scene_test')
index a8f9f8f..229de74 100644 (file)
@@ -553,7 +553,7 @@ class ClientController
                     out << "Platform version: " << platformInfo.getPlatformVersion() << std::endl;
                     out << "Manufacturer name: " << platformInfo.getManufacturerName() << std::endl;
                     out << "Manufacturer url: " << platformInfo.getManufacturerUrl() << std::endl;
-                    out << "Modle number: " << platformInfo.getModelNumber() << std::endl;
+                    out << "Model number: " << platformInfo.getModelNumber() << std::endl;
                     out << "Date of manufacture: " << platformInfo.getDateOfManfacture() << std::endl;
                     out << "Operatio system version: " << platformInfo.getOSVersion() << std::endl;
                     out << "Hardware version: " << platformInfo.getHardwareVersion() << std::endl;
index da66dbf..531e0cb 100644 (file)
@@ -37,13 +37,13 @@ things_manager_env.AppendUnique(CPPPATH = ['../../extlibs/timer', 'sdk/inc', 'sd
 
 things_manager_env.PrependUnique(LIBS = ['oc', 'octbstack'])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
     things_manager_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
     if target_os != 'android':
         things_manager_env.AppendUnique(CXXFLAGS = ['-pthread'])
         things_manager_env.AppendUnique(LIBS = ['pthread'])
 
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
     things_manager_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
 
 if target_os == 'android':
index 7c95953..de8c2c3 100755 (executable)
@@ -25,9 +25,7 @@
 #include <vector>
 #include <cstdio>
 #include <iostream>
-
 #include <ctime>
-
 #include <timer.h>
 
 using namespace std;
index d6232a0..9cb0683 100644 (file)
@@ -27,7 +27,7 @@ tm_jni_env.AppendUnique(CPPPATH = [tm_sdk+'/inc'])
 tm_jni_env.AppendUnique(CPPPATH = [base_jni])
 tm_jni_env.AppendUnique(CPPPATH = ['tm/inc', 'jniutil/inc', extlibs+'/timer/'])
 
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
     tm_jni_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
 
 ######################################################################
index 8bbe52f..1568447 100755 (executable)
@@ -25,7 +25,9 @@
 
 #include <algorithm>
 #include <thread>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 #include <string.h>
 
 #include "GroupManager.h"
index 461103a..8c49f7e 100644 (file)
@@ -69,7 +69,7 @@ ThingsManager_gtest_env.AppendUnique(
                 '../../../extlibs/timer'
         ])
 
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
         ThingsManager_gtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
         if target_os != 'android':
                 ThingsManager_gtest_env.AppendUnique(CXXFLAGS = ['-pthread'])
index 1dfd837..b6ca64b 100644 (file)
@@ -94,6 +94,9 @@ elif target_os == 'ios':
 elif target_os == 'darwin':
        lib_env.AppendUnique(CPPPATH = ['/usr/local/include'])
        lib_env.AppendUnique(LIBPATH = ['/usr/local/lib'])
+elif target_os == 'windows':
+       boost_path = os.path.join(src_dir,'extlibs','boost','boost')
+       lib_env.AppendUnique(CPPPATH = [boost_path])
 
 Import('env')
 lib_env.AppendUnique(LIBPATH = env.get('BUILD_DIR'))
index 27c7dd4..0d91809 100755 (executable)
@@ -85,7 +85,7 @@ echo "Framework: Copying includes..."
 cp -r  resource/csdk/stack/include/*.h  $FRAMEWORK_BUNDLE/Headers
 cp -r  resource/csdk/ocsocket/include/*.h  $FRAMEWORK_BUNDLE/Headers
 cp -r  resource/c_common/ocrandom/include/*.h  $FRAMEWORK_BUNDLE/Headers
-cp -r  resource/csdk/ocmalloc/include/*.h  $FRAMEWORK_BUNDLE/Headers
+cp -r  resource/c_common/oic_malloc/include/*.h  $FRAMEWORK_BUNDLE/Headers
 
 echo "Framework: Creating plist..."
 cat > $FRAMEWORK_BUNDLE/Resources/Info.plist <<EOF
index 45a0f74..9026920 100755 (executable)
@@ -86,7 +86,7 @@ find $OUTDIR/objs -name "*.o" | xargs rm
 echo "Framework: Copying includes..."
 cp -r  resource/csdk/stack/include/*.h  $FRAMEWORK_BUNDLE/Headers
 cp -r  resource/c_common/ocrandom/include/*.h  $FRAMEWORK_BUNDLE/Headers
-cp -r  resource/csdk/ocmalloc/include/*.h  $FRAMEWORK_BUNDLE/Headers
+cp -r  resource/c_common/oic_malloc/include/*.h  $FRAMEWORK_BUNDLE/Headers
 
 echo "Framework: Creating plist..."
 cat > $FRAMEWORK_BUNDLE/Resources/Info.plist <<EOF
index 5ec0bad..1a429f6 100644 (file)
@@ -43,7 +43,11 @@ def run_test(env, xml_file, test):
 
     test_cmd = os.path.join(build_dir, test)
 
-    if xml_file:
+    have_valgrind = False
+    if env.get('TARGET_OS') not in ['windows']:
+        have_valgrind = True
+
+    if xml_file and have_valgrind:
         # Environment variables to be made available during the
         # Valgrind run.
         valgrind_environment = ''
index 557e2a1..f0f0810 100644 (file)
@@ -346,7 +346,7 @@ def generate( env ) :
 
 
     # read the tools on *nix systems and sets the default parameters
-    elif env["PLATFORM"] in ["darwin", "linux", "posix"] :
+    elif env["PLATFORM"] in ["darwin", "linux", "posix", "msys"] :
 
         if env.WhereIs("unzip") :
             toolset["EXTRACTOR"]["ZIP"]["RUN"]             = "unzip"
index 0f0fc35..4177f08 100644 (file)
@@ -1,5 +1,5 @@
 Name: iotivity
-Version: 1.1.0
+Version: 1.1.1
 Release: 0
 Summary: IoT Connectivity sponsored by the OIC
 Group: Network & Connectivity/Other