diff options
author | Youngjae Shin <yj99.shin@samsung.com> | 2016-08-02 13:21:12 +0900 |
---|---|---|
committer | Youngjae Shin <yj99.shin@samsung.com> | 2016-08-02 13:39:19 +0900 |
commit | e2559281e01189185cb2d85edca592f2875d6878 (patch) | |
tree | f9b97e8412210f4825157f88afbda39538f966ca | |
parent | f5025d7067356e547eecff643d71912bf8cf008e (diff) | |
parent | 1cee1631595cac6a6394ac2e0b365c6dd5a42c68 (diff) | |
download | iotivity-e2559281e01189185cb2d85edca592f2875d6878.tar.gz iotivity-e2559281e01189185cb2d85edca592f2875d6878.tar.bz2 iotivity-e2559281e01189185cb2d85edca592f2875d6878.zip |
Merge branch 'upstream' into tizen
Conflicts:
packaging/iotivity.spec
Change-Id: I0ebb075dbed68e747ac78ebfc36ef2ffb2b5a24a
400 files changed, 18404 insertions, 6278 deletions
diff --git a/android/android_api/base/build.gradle b/android/android_api/base/build.gradle index 7deb01cb0..a0b52ae6a 100755 --- a/android/android_api/base/build.gradle +++ b/android/android_api/base/build.gradle @@ -41,7 +41,7 @@ android { minSdkVersion 21
targetSdkVersion 21
versionCode 1
- versionName "1.1"
+ versionName "1.1.1"
buildConfigField 'int', 'SECURED', SECURED
}
buildTypes {
diff --git a/android/android_api/base/jni/Android.mk b/android/android_api/base/jni/Android.mk index cc43275bf..51d9dcd49 100644 --- a/android/android_api/base/jni/Android.mk +++ b/android/android_api/base/jni/Android.mk @@ -58,7 +58,7 @@ LOCAL_SRC_FILES := JniOcStack.cpp \ JniEntityHandler.cpp \
JniOnResourceFoundListener.cpp \
JniOnDeviceInfoListener.cpp \
- JniOnPlatformInfoListener.cpp \
+ JniOnPlatformInfoListener.cpp \
JniOnPresenceListener.cpp \
JniOnGetListener.cpp \
JniOnPutListener.cpp \
@@ -74,15 +74,18 @@ LOCAL_SRC_FILES := JniOcStack.cpp \ JniOcPlatform.cpp \
JniOcResource.cpp \
JniOcResourceIdentifier.cpp \
- JniOcSecurity.cpp
+ JniOcSecurity.cpp \
+ JniOnDPDevicesFoundListener.cpp \
+ JniOnDirectPairingListener.cpp \
+ JniOcDirectPairDevice.cpp
ifeq ($(SECURED), 1)
-LOCAL_SRC_FILES += JniOcSecureResource.cpp \
- JniOcProvisioning.cpp \
- JniSecureUtils.cpp \
- JniProvisionResultListner.cpp \
- JniPinCheckListener.cpp \
- JniDisplayPinListener.cpp
-endif
+ LOCAL_SRC_FILES += JniOcSecureResource.cpp \
+ JniOcProvisioning.cpp \
+ JniSecureUtils.cpp \
+ JniProvisionResultListner.cpp \
+ JniPinCheckListener.cpp \
+ JniDisplayPinListener.cpp
+ endif
LOCAL_LDLIBS := -llog
LOCAL_STATIC_LIBRARIES := android-oc
@@ -112,6 +115,7 @@ LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/provisioning/include LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/provisioning/include/oxm/
LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/provisioning/include/internal
LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/include
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/include/internal
LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/connectivity/api
LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/connectivity/lib/libcoap-4.1.1
include $(BUILD_SHARED_LIBRARY)
diff --git a/android/android_api/base/jni/JniOcDirectPairDevice.cpp b/android/android_api/base/jni/JniOcDirectPairDevice.cpp new file mode 100644 index 000000000..535bebc58 --- /dev/null +++ b/android/android_api/base/jni/JniOcDirectPairDevice.cpp @@ -0,0 +1,132 @@ +/* +* //****************************************************************** +* // +* // 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 index 000000000..505bac2d6 --- /dev/null +++ b/android/android_api/base/jni/JniOcDirectPairDevice.h @@ -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 + diff --git a/android/android_api/base/jni/JniOcPlatform.cpp b/android/android_api/base/jni/JniOcPlatform.cpp index 93029c96c..82f693f22 100644 --- a/android/android_api/base/jni/JniOcPlatform.cpp +++ b/android/android_api/base/jni/JniOcPlatform.cpp @@ -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 @@ -703,6 +847,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 @@ -1070,20 +1353,44 @@ 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) + { + ThrowOcException(OC_STACK_INVALID_PARAM, "device type cannot be null"); + return; + } + + OCResourcePayloadAddStringLL(&deviceInfo.types, env->GetStringUTFChars(jStr, nullptr)); + if (env->ExceptionCheck()) return; + + env->DeleteLocalRef(jStr); + } } catch (std::exception &e) { diff --git a/android/android_api/base/jni/JniOcPlatform.h b/android/android_api/base/jni/JniOcPlatform.h index cfd685300..a45f05912 100644 --- a/android/android_api/base/jni/JniOcPlatform.h +++ b/android/android_api/base/jni/JniOcPlatform.h @@ -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 diff --git a/android/android_api/base/jni/JniOcSecureResource.cpp b/android/android_api/base/jni/JniOcSecureResource.cpp index 77c8dc6df..4b12e525e 100644 --- a/android/android_api/base/jni/JniOcSecureResource.cpp +++ b/android/android_api/base/jni/JniOcSecureResource.cpp @@ -22,6 +22,9 @@ #include "JniOcSecureResource.h" #include "JniSecureUtils.h" +#include "aclresource.h" +#include "oic_malloc.h" +#include "oic_string.h" namespace PH = std::placeholders; JniOcSecureResource::JniOcSecureResource(std::shared_ptr<OCSecureResource> device) @@ -210,32 +213,112 @@ OCStackResult JniOcSecureResource::provisionACL(JNIEnv* env, jobject _acl, jobje { OCStackResult ret; JniProvisionResultListner *resultListener = AddProvisionResultListener(env, jListener); - OicSecAcl_t *acl = new OicSecAcl_t; + OicSecAcl_t *acl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t)); if (!acl) { return OC_STACK_NO_MEMORY; } - acl->next = nullptr; - if (OC_STACK_OK != JniSecureUtils::convertJavaACLToOCAcl(env, _acl, acl)) { - delete acl; + JniSecureUtils::FreeACLList(acl); return OC_STACK_ERROR; } ResultCallBack resultCallback = [acl, resultListener](PMResultList_t *result, int hasError) { - delete acl; + JniSecureUtils::FreeACLList(acl); resultListener->ProvisionResultCallback(result, hasError, ListenerFunc::PROVISIONACL); }; ret = m_sharedSecureResource->provisionACL(acl, resultCallback); if (ret != OC_STACK_OK) { - delete acl; + JniSecureUtils::FreeACLList(acl); + } + 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; } @@ -259,7 +342,7 @@ OCStackResult JniOcSecureResource::provisionPairwiseDevices(JNIEnv* env, jint ty if (_acl1) { - acl1 = new OicSecAcl_t; + acl1 = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t)); if (!acl1) { return OC_STACK_NO_MEMORY; @@ -267,45 +350,43 @@ OCStackResult JniOcSecureResource::provisionPairwiseDevices(JNIEnv* env, jint ty if (OC_STACK_OK != JniSecureUtils::convertJavaACLToOCAcl(env, _acl1, acl1)) { - delete acl1; + JniSecureUtils::FreeACLList(acl1); return OC_STACK_ERROR; } - acl1->next = nullptr; } if (_acl2) { - acl2 = new OicSecAcl_t; + acl2 = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t)); if (!acl2) { - delete acl1; + JniSecureUtils::FreeACLList(acl1); return OC_STACK_NO_MEMORY; } if (OC_STACK_OK != JniSecureUtils::convertJavaACLToOCAcl(env, _acl2, acl2)) { - delete acl2; + JniSecureUtils::FreeACLList(acl1); + JniSecureUtils::FreeACLList(acl2); return OC_STACK_ERROR; } - acl2->next = nullptr; } ResultCallBack resultCallback = [acl1, acl2, resultListener](PMResultList_t *result, int hasError) { - delete acl1; - delete acl2; + JniSecureUtils::FreeACLList(acl1); + JniSecureUtils::FreeACLList(acl2); resultListener->ProvisionResultCallback(result, hasError, ListenerFunc::PROVISIONPAIRWISEDEVICES); }; - ret = m_sharedSecureResource->provisionPairwiseDevices(cred, acl1, *device2->getDevicePtr(), acl2, resultCallback); if (ret != OC_STACK_OK) { - delete acl1; - delete acl2; + JniSecureUtils::FreeACLList(acl1); + JniSecureUtils::FreeACLList(acl2); } return ret; } @@ -543,6 +624,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; */ diff --git a/android/android_api/base/jni/JniOcSecureResource.h b/android/android_api/base/jni/JniOcSecureResource.h index 0b98f75fb..d071e968d 100644 --- a/android/android_api/base/jni/JniOcSecureResource.h +++ b/android/android_api/base/jni/JniOcSecureResource.h @@ -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; */ diff --git a/android/android_api/base/jni/JniOcStack.cpp b/android/android_api/base/jni/JniOcStack.cpp index c5c3d7db4..18d01603a 100644 --- a/android/android_api/base/jni/JniOcStack.cpp +++ b/android/android_api/base/jni/JniOcStack.cpp @@ -25,6 +25,18 @@ #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,11 @@ jclass g_cls_OcResourceIdentifier = nullptr; jclass g_cls_OcProvisionResult = nullptr; jclass g_cls_OcSecureResource = nullptr; jclass g_cls_OcOicSecAcl = nullptr; +jclass g_cls_OcOicSecAcl_ace = nullptr; +jclass g_cls_OcOicSecAcl_resr = nullptr; +jclass g_cls_OcOicSecAcl_validity = nullptr; +jclass g_cls_OcOicSecPdAcl = nullptr; +jclass g_cls_OcDirectPairDevice = nullptr; jmethodID g_mid_Integer_ctor = nullptr; jmethodID g_mid_Double_ctor = nullptr; @@ -94,14 +111,30 @@ 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_OcOicSecAcl_get_subject = nullptr; -jmethodID g_mid_OcOicSecAcl_get_resources_cnt = nullptr; -jmethodID g_mid_OcOicSecAcl_get_resources = nullptr; -jmethodID g_mid_OcOicSecAcl_get_permission = nullptr; -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_OcDirectPairDevice_ctor = nullptr; +jmethodID g_mid_OcDirectPairDevice_dev_ctor = 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; + +jmethodID g_mid_OcOicSecAcl_get_aces = nullptr; +jmethodID g_mid_OcOicSecAcl_ace_get_subjectID = nullptr; +jmethodID g_mid_OcOicSecAcl_ace_get_permissions = nullptr; +jmethodID g_mid_OcOicSecAcl_ace_get_resources = nullptr; +jmethodID g_mid_OcOicSecAcl_ace_get_validities = nullptr; +jmethodID g_mid_OcOicSecAcl_resr_get_href = nullptr; +jmethodID g_mid_OcOicSecAcl_resr_get_rel = nullptr; +jmethodID g_mid_OcOicSecAcl_resr_get_types = nullptr; +jmethodID g_mid_OcOicSecAcl_resr_get_typeLen = nullptr; +jmethodID g_mid_OcOicSecAcl_resr_get_interfaces = nullptr; +jmethodID g_mid_OcOicSecAcl_validity_get_getPeriod = nullptr; +jmethodID g_mid_OcOicSecAcl_validity_get_recurrences = nullptr; +jmethodID g_mid_OcOicSecAcl_validity_get_recurrenceLen = nullptr; +jmethodID g_mid_OcOicSecAcl_resr_get_interfaceLen = nullptr; jmethodID g_mid_OcOicSecAcl_get_rownerID = nullptr; jobject getOcException(JNIEnv* env, const char* file, const char* functionName, @@ -141,7 +174,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 +182,392 @@ 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; + g_mid_OcOicSecAcl_get_rownerID = env->GetMethodID(g_cls_OcOicSecAcl, "getRownerID", "()Ljava/lang/String;"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_rownerID); + + g_mid_OcOicSecAcl_get_aces = env->GetMethodID(g_cls_OcOicSecAcl, "getOicSecAces", "()[Lorg/iotivity/base/OicSecAce;"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_aces); + + //OicSecAce + clazz = env->FindClass("org/iotivity/base/OicSecAce"); + VERIFY_VARIABLE_NULL(clazz); + g_cls_OcOicSecAcl_ace = (jclass)env->NewGlobalRef(clazz); + env->DeleteLocalRef(clazz); + + g_mid_OcOicSecAcl_ace_get_subjectID = env->GetMethodID(g_cls_OcOicSecAcl_ace, "getSubjectID","()Ljava/lang/String;"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_ace_get_subjectID); - g_mid_OcOicSecAcl_get_resources_cnt = env->GetMethodID(g_cls_OcOicSecAcl, "getResourcesCount", "()I"); - if (!g_mid_OcOicSecAcl_get_resources_cnt) return JNI_ERR; + g_mid_OcOicSecAcl_ace_get_permissions = env->GetMethodID(g_cls_OcOicSecAcl_ace, "getPermission","()I"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_ace_get_permissions); - g_mid_OcOicSecAcl_get_resources = env->GetMethodID(g_cls_OcOicSecAcl, "getResources", "(I)Ljava/lang/String;"); - if (!g_mid_OcOicSecAcl_get_resources) return JNI_ERR; + g_mid_OcOicSecAcl_ace_get_resources = env->GetMethodID(g_cls_OcOicSecAcl_ace, "getResources","()[Lorg/iotivity/base/OicSecResr;"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_ace_get_resources); - g_mid_OcOicSecAcl_get_permission = env->GetMethodID(g_cls_OcOicSecAcl, "getPermission", "()I"); - if (!g_mid_OcOicSecAcl_get_permission) return JNI_ERR; + g_mid_OcOicSecAcl_ace_get_validities = env->GetMethodID(g_cls_OcOicSecAcl_ace, "getValidities","()[Lorg/iotivity/base/OicSecValidity;"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_ace_get_validities); - g_mid_OcOicSecAcl_get_periods_cnt = env->GetMethodID(g_cls_OcOicSecAcl, "getPeriodsCount", "()I"); - if (!g_mid_OcOicSecAcl_get_periods_cnt) return JNI_ERR; + //OicSecResr + clazz = env->FindClass("org/iotivity/base/OicSecResr"); + VERIFY_VARIABLE_NULL(clazz); + g_cls_OcOicSecAcl_resr = (jclass)env->NewGlobalRef(clazz); + env->DeleteLocalRef(clazz); - g_mid_OcOicSecAcl_get_periods = env->GetMethodID(g_cls_OcOicSecAcl, "getPeriods", "(I)Ljava/lang/String;"); - if (!g_mid_OcOicSecAcl_get_periods) return JNI_ERR; + g_mid_OcOicSecAcl_resr_get_href = env->GetMethodID(g_cls_OcOicSecAcl_resr, "getHref","()Ljava/lang/String;"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_resr_get_href); - g_mid_OcOicSecAcl_get_recurrences = env->GetMethodID(g_cls_OcOicSecAcl, "getRecurrences", "(I)Ljava/lang/String;"); - if (!g_mid_OcOicSecAcl_get_recurrences) return JNI_ERR; + g_mid_OcOicSecAcl_resr_get_rel = env->GetMethodID(g_cls_OcOicSecAcl_resr, "getRel","()Ljava/lang/String;"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_resr_get_rel); - g_mid_OcOicSecAcl_get_rownerID = env->GetMethodID(g_cls_OcOicSecAcl, "getRownerID", "()Ljava/lang/String;"); - if (!g_mid_OcOicSecAcl_get_rownerID) return JNI_ERR; + g_mid_OcOicSecAcl_resr_get_types = env->GetMethodID(g_cls_OcOicSecAcl_resr, "getTypes","(I)Ljava/lang/String;"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_resr_get_types); + + g_mid_OcOicSecAcl_resr_get_typeLen = env->GetMethodID(g_cls_OcOicSecAcl_resr, "getTypeLen","()I"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_resr_get_typeLen); + + g_mid_OcOicSecAcl_resr_get_interfaces = env->GetMethodID(g_cls_OcOicSecAcl_resr, "getInterfaces","(I)Ljava/lang/String;"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_resr_get_interfaces); + + g_mid_OcOicSecAcl_resr_get_interfaceLen = env->GetMethodID(g_cls_OcOicSecAcl_resr, "getInterfaceLen","()I"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_resr_get_interfaceLen); + + //OicSecAcl$OicSecValidity + clazz = env->FindClass("org/iotivity/base/OicSecValidity"); + VERIFY_VARIABLE_NULL(clazz); + g_cls_OcOicSecAcl_validity = (jclass)env->NewGlobalRef(clazz); + env->DeleteLocalRef(clazz); + + g_mid_OcOicSecAcl_validity_get_getPeriod = env->GetMethodID(g_cls_OcOicSecAcl_validity, "getPeriod","()Ljava/lang/String;"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_validity_get_getPeriod); + + g_mid_OcOicSecAcl_validity_get_recurrences = env->GetMethodID(g_cls_OcOicSecAcl_validity, "getRecurrences","(I)Ljava/lang/String;"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_validity_get_recurrences); + + g_mid_OcOicSecAcl_validity_get_recurrenceLen = env->GetMethodID(g_cls_OcOicSecAcl_validity, "getRecurrenceLen","()I"); + VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_validity_get_recurrenceLen); + + //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; } @@ -509,4 +618,7 @@ 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 + env->DeleteGlobalRef(g_cls_OcOicSecAcl_ace); + env->DeleteGlobalRef(g_cls_OcOicSecAcl_resr); + env->DeleteGlobalRef(g_cls_OcOicSecAcl_validity); +} diff --git a/android/android_api/base/jni/JniOcStack.h b/android/android_api/base/jni/JniOcStack.h index b9f2ccdf5..243ce4cd0 100644 --- a/android/android_api/base/jni/JniOcStack.h +++ b/android/android_api/base/jni/JniOcStack.h @@ -82,6 +82,12 @@ 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 jclass g_cls_OcOicSecAcl_ace; +extern jclass g_cls_OcOicSecAcl_resr; +extern jclass g_cls_OcOicSecAcl_validity; extern jmethodID g_mid_Integer_ctor; extern jmethodID g_mid_Double_ctor; @@ -114,14 +120,30 @@ 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_OcOicSecAcl_get_subject; -extern jmethodID g_mid_OcOicSecAcl_get_resources_cnt; -extern jmethodID g_mid_OcOicSecAcl_get_resources; -extern jmethodID g_mid_OcOicSecAcl_get_permission; -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_OcDirectPairDevice_ctor; +extern jmethodID g_mid_OcDirectPairDevice_dev_ctor; + extern jmethodID g_mid_OcOicSecAcl_get_rownerID; +extern jmethodID g_mid_OcOicSecAcl_get_aces; +extern jmethodID g_mid_OcOicSecAcl_ace_get_subjectID; +extern jmethodID g_mid_OcOicSecAcl_ace_get_permissions; +extern jmethodID g_mid_OcOicSecAcl_ace_get_resources; +extern jmethodID g_mid_OcOicSecAcl_ace_get_validities; +extern jmethodID g_mid_OcOicSecAcl_resr_get_href; +extern jmethodID g_mid_OcOicSecAcl_resr_get_rel; +extern jmethodID g_mid_OcOicSecAcl_resr_get_types; +extern jmethodID g_mid_OcOicSecAcl_resr_get_typeLen; +extern jmethodID g_mid_OcOicSecAcl_resr_get_interfaces; +extern jmethodID g_mid_OcOicSecAcl_resr_get_interfaceLen; +extern jmethodID g_mid_OcOicSecAcl_validity_get_getPeriod; +extern jmethodID g_mid_OcOicSecAcl_validity_get_recurrences; +extern jmethodID g_mid_OcOicSecAcl_validity_get_recurrenceLen; +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 +173,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 +204,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 index 000000000..5c5d900ac --- /dev/null +++ b/android/android_api/base/jni/JniOnDPDevicesFoundListener.cpp @@ -0,0 +1,165 @@ +/* +* //****************************************************************** +* // +* // 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; + 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"; + } + 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 index 000000000..88acb61e8 --- /dev/null +++ b/android/android_api/base/jni/JniOnDPDevicesFoundListener.h @@ -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 diff --git a/android/android_api/base/jni/JniOnDirectPairingListener.cpp b/android/android_api/base/jni/JniOnDirectPairingListener.cpp new file mode 100644 index 000000000..f580079a4 --- /dev/null +++ b/android/android_api/base/jni/JniOnDirectPairingListener.cpp @@ -0,0 +1,129 @@ +/* +* //****************************************************************** +* // +* // 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; + 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; + 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 index 000000000..8ec2b7e69 --- /dev/null +++ b/android/android_api/base/jni/JniOnDirectPairingListener.h @@ -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 diff --git a/android/android_api/base/jni/JniProvisionResultListner.cpp b/android/android_api/base/jni/JniProvisionResultListner.cpp index 6b9fd0477..a600e6456 100644 --- a/android/android_api/base/jni/JniProvisionResultListner.cpp +++ b/android/android_api/base/jni/JniProvisionResultListner.cpp @@ -109,6 +109,11 @@ void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result, calledFunc = "provisionPairwiseDevicesListener"; } break; + case ListenerFunc::PROVISIONDIRECTPAIRING: + { + calledFunc = "provisionDirectPairingListener"; + } + break; default: { checkExAndRemoveListener(env); diff --git a/android/android_api/base/jni/JniProvisionResultListner.h b/android/android_api/base/jni/JniProvisionResultListner.h index 6df56d706..8bf52421e 100644 --- a/android/android_api/base/jni/JniProvisionResultListner.h +++ b/android/android_api/base/jni/JniProvisionResultListner.h @@ -35,7 +35,8 @@ enum class ListenerFunc PROVISIONCREDENTIALS, UNLINKDEVICES, REMOVEDEVICE, - PROVISIONPAIRWISEDEVICES + PROVISIONPAIRWISEDEVICES, + PROVISIONDIRECTPAIRING }; class JniProvisionResultListner diff --git a/android/android_api/base/jni/JniSecureUtils.cpp b/android/android_api/base/jni/JniSecureUtils.cpp index 24e4f57f3..718bb4aed 100644 --- a/android/android_api/base/jni/JniSecureUtils.cpp +++ b/android/android_api/base/jni/JniSecureUtils.cpp @@ -21,7 +21,9 @@ */ #include "JniSecureUtils.h" +#include "JniOcStack.h" #include "JniOcSecureResource.h" +#include "oic_malloc.h" #include "srmutility.h" #include "base64.h" @@ -35,7 +37,15 @@ jobject JniSecureUtils::convertProvisionresultVectorToJavaList(JNIEnv *env, cons for (size_t i = 0; i < result->size(); ++i) { - jstring jStr = env->NewStringUTF((convertUUIDtoStr(result->at(i).deviceId).c_str())); + char *Str = NULL; + + if (OC_STACK_OK != ConvertUuidToStr(&(result->at(i).deviceId), &Str)) + { + return nullptr; + } + jstring jStr = env->NewStringUTF(Str); + OICFree(Str); + if (!jStr) { return nullptr; @@ -117,7 +127,15 @@ jobject JniSecureUtils::convertUUIDVectorToJavaStrList(JNIEnv *env, UuidList_t & } for (size_t i = 0; i < vector.size(); ++i) { - jstring jStr = env->NewStringUTF((convertUUIDtoStr(vector[i])).c_str()); + char *Str = NULL; + + if (OC_STACK_OK != ConvertUuidToStr(&(vector[i]), &Str)) + { + return nullptr; + } + jstring jStr = env->NewStringUTF(Str); + OICFree(Str); + if (!jStr) { return nullptr; @@ -132,19 +150,270 @@ jobject JniSecureUtils::convertUUIDVectorToJavaStrList(JNIEnv *env, UuidList_t & return jList; } +static void freeValidities(OicSecValidity_t *head) +{ + OicSecValidity_t *tmp = head; + while(tmp != NULL) + { + head = head->next; + free(tmp->recurrences); + free(tmp); + tmp = head; + } +} + +static void freeResources(OicSecRsrc_t *head) +{ + OicSecRsrc_t *tmp = head; + while(tmp != NULL) + { + head = head->next; + free(tmp->types); + free(tmp->interfaces); + free(tmp); + tmp = head; + } +} + +void JniSecureUtils::FreeACLList(OicSecAcl_t *acl) +{ + if (acl) + { + if (acl->aces) + { + freeResources(acl->aces->resources); + freeValidities(acl->aces->validities); + OICFree(acl->aces); + } + OICFree(acl); + } +} + +static OicSecValidity_t* getValiditiesList(JNIEnv *env, jobject validityObject) +{ + jstring jData; + jobjectArray valList = (jobjectArray)env->CallObjectMethod(validityObject, g_mid_OcOicSecAcl_ace_get_validities); + if (!valList || env->ExceptionCheck()) + { + return nullptr; + } + int nr_validities = env->GetArrayLength(valList); + + OicSecValidity_t *valHead = NULL; + + for (int i = 0 ; i < nr_validities; i++) + { + OicSecValidity_t *tmp = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t)); + if (NULL == tmp) + { + LOGE("Failed to allocate memory"); + freeValidities(valHead); + return nullptr; + } + + jobject element = env->GetObjectArrayElement(valList, i); + if (!element || env->ExceptionCheck()) + { + OICFree(tmp); + freeValidities(valHead); + return nullptr; + } + + jData = (jstring)env->CallObjectMethod(element, g_mid_OcOicSecAcl_validity_get_getPeriod); + if (!jData || env->ExceptionCheck()) + { + OICFree(tmp); + freeValidities(valHead); + return nullptr; + } + tmp->period = (char*)env->GetStringUTFChars(jData, 0); + + jint jrecurrenceLen = (jint) env->CallIntMethod(element, + g_mid_OcOicSecAcl_validity_get_recurrenceLen); + if (env->ExceptionCheck()) + { + OICFree(tmp); + freeValidities(valHead); + return nullptr; + } + tmp->recurrenceLen = (int)jrecurrenceLen; + + if (jrecurrenceLen > 0) + { + jvalue argv[1]; + tmp->recurrences = (char**)OICCalloc(jrecurrenceLen, sizeof(char*)); + + for (int i = 0 ; i < jrecurrenceLen; i++) + { + argv[0].i = i; + jData = (jstring)env->CallObjectMethodA(element, g_mid_OcOicSecAcl_validity_get_recurrences, argv); + if (!jData || env->ExceptionCheck()) + { + OICFree(tmp->recurrences); + OICFree(tmp); + freeValidities(valHead); + return nullptr; + } + tmp->recurrences[i] = (char*)env->GetStringUTFChars(jData, 0); + } + } + if (NULL == valHead) + { + valHead = tmp; + } + else + { + OicSecValidity_t *ptr = valHead; + while(ptr->next != NULL) ptr = ptr->next; + ptr->next = tmp; + tmp->next = NULL; + } + env->DeleteLocalRef(element); + } + return valHead; +} + +static OicSecRsrc_t * getResourcesList(JNIEnv *env, jobject resourceObject) +{ + jstring jData; + + jobjectArray rescList = (jobjectArray)env->CallObjectMethod(resourceObject, g_mid_OcOicSecAcl_ace_get_resources); + if (!rescList || env->ExceptionCheck()) + { + return nullptr; + } + + int nr_resc = env->GetArrayLength(rescList); + OicSecRsrc_t *rescHead = NULL; + + for (int i = 0 ; i < nr_resc; i++) + { + OicSecRsrc_t *tmp = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t)); + if (NULL == tmp) + { + LOGE("Failed to allocate memory"); + freeResources(rescHead); + return nullptr; + } + jobject element = env->GetObjectArrayElement(rescList, i); + if (!element || env->ExceptionCheck()) + { + OICFree(tmp); + freeResources(rescHead); + return nullptr; + } + jData = (jstring)env->CallObjectMethod(element, g_mid_OcOicSecAcl_resr_get_href); + if (!jData || env->ExceptionCheck()) + { + OICFree(tmp); + freeResources(rescHead); + return nullptr; + } + tmp->href = (char*)env->GetStringUTFChars(jData, 0); + + jData = (jstring)env->CallObjectMethod(element, g_mid_OcOicSecAcl_resr_get_rel); + if (!jData || env->ExceptionCheck()) + { + OICFree(tmp); + freeResources(rescHead); + return nullptr; + } + tmp->rel = (char*)env->GetStringUTFChars(jData, 0); + + jint len = (jint) env->CallIntMethod(element, g_mid_OcOicSecAcl_resr_get_typeLen); + if (env->ExceptionCheck()) + { + OICFree(tmp); + freeResources(rescHead); + return nullptr; + } + tmp->typeLen = (int)len; + if (len > 0) + { + jvalue argv[1]; + tmp->types = (char**)OICCalloc(len, sizeof(char*)); + if (NULL == tmp->types) + { + LOGE("Failed to allocate memory"); + return nullptr; + } + + for (int i = 0 ; i < len; i++) + { + argv[0].i = i; + jData = (jstring)env->CallObjectMethodA(element, g_mid_OcOicSecAcl_resr_get_types, argv); + if (!jData || env->ExceptionCheck()) + { + OICFree(tmp->types); + OICFree(tmp); + freeResources(rescHead); + return nullptr; + } + tmp->types[i] = (char*)env->GetStringUTFChars(jData, 0); + } + } + + len = (jint) env->CallIntMethod(element, g_mid_OcOicSecAcl_resr_get_interfaceLen); + if (env->ExceptionCheck()) + { + OICFree(tmp->types); + OICFree(tmp); + freeResources(rescHead); + return nullptr; + } + tmp->interfaceLen = len; + if (len > 0) + { + jvalue argv[1]; + tmp->interfaces = (char**)OICCalloc(len, sizeof(char*)); + + for (int i = 0 ; i < len; i++) + { + argv[0].i = i; + jData = (jstring)env->CallObjectMethodA(element, g_mid_OcOicSecAcl_resr_get_interfaces, argv); + if (!jData || env->ExceptionCheck()) + { + OICFree(tmp->types); + OICFree(tmp); + freeResources(rescHead); + return nullptr; + } + tmp->interfaces[i] = (char*)env->GetStringUTFChars(jData, 0); + } + } + + if (NULL == rescHead) + { + rescHead = tmp; + } + else + { + OicSecRsrc_t *ptr = rescHead; + while(ptr->next != NULL) ptr = ptr->next; + ptr->next = tmp; + tmp->next = NULL; + } + env->DeleteLocalRef(element); + } + return rescHead; +} + OCStackResult JniSecureUtils::convertJavaACLToOCAcl(JNIEnv *env, jobject in, OicSecAcl_t *acl) { jstring jData; - jvalue args[1]; - jData = (jstring) env->CallObjectMethod(in, g_mid_OcOicSecAcl_get_subject); + jData = (jstring) env->CallObjectMethod(in, g_mid_OcOicSecAcl_get_rownerID); if (!jData || env->ExceptionCheck()) { return OC_STACK_ERROR; } char *str = (char*) env->GetStringUTFChars(jData, 0); - if (OC_STACK_OK == ConvertStrToUuid(str, &acl->subject)) + if (!str) + { + return OC_STACK_ERROR; + } + if (OC_STACK_OK == ConvertStrToUuid(str, &acl->rownerID)) { env->ReleaseStringUTFChars(jData, str); } @@ -153,82 +422,160 @@ OCStackResult JniSecureUtils::convertJavaACLToOCAcl(JNIEnv *env, jobject in, Oic return OC_STACK_ERROR; } - jint jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecAcl_get_resources_cnt); + jobjectArray acesList = (jobjectArray)env->CallObjectMethod(in, g_mid_OcOicSecAcl_get_aces); + + if (!acesList || env->ExceptionCheck()) + { + return OC_STACK_ERROR; + } + + int nr_aces = env->GetArrayLength(acesList); + + OicSecAce_t *acesHead = NULL; + + for (int i = 0 ; i < nr_aces; i++) + { + OicSecAce_t *tmp = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t)); + + jobject element = env->GetObjectArrayElement(acesList, i); + if (!element || env->ExceptionCheck()) + { + return OC_STACK_ERROR; + } + + jData = (jstring) env->CallObjectMethod(element, g_mid_OcOicSecAcl_ace_get_subjectID); + if (!jData || env->ExceptionCheck()) + { + return OC_STACK_ERROR; + } + + str = (char*) env->GetStringUTFChars(jData, 0); + + if (!str) + { + return OC_STACK_ERROR; + } + if (OC_STACK_OK == ConvertStrToUuid(str, &tmp->subjectuuid)) + { + env->ReleaseStringUTFChars(jData, str); + } + else + { + return OC_STACK_ERROR; + } + + jint perm = (jint)env->CallIntMethod(element, g_mid_OcOicSecAcl_ace_get_permissions); + tmp->permission = (uint16_t)perm; + if (nullptr == (tmp->resources = getResourcesList(env, element))) + { + return OC_STACK_ERROR; + } + + tmp->validities = NULL; //TODO Seems Validities CBOR conversion is broken in C stack +#if 0 + if (nullptr == (tmp->validities = getValiditiesList(env, element))) + { + return OC_STACK_ERROR; + } +#endif + if (NULL == acesHead) + { + acesHead = tmp; + } + else + { + OicSecAce_t *ptr = acesHead; + while(ptr->next != NULL) ptr = ptr->next; + ptr->next = tmp; + tmp->next = NULL; + } + } + acl->aces = acesHead; + 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; } - acl->resourcesLen = jCount; - acl->resources = new char*[jCount]; + 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_OcOicSecAcl_get_resources, args); + jData = (jstring) env->CallObjectMethodA(in, g_mid_OcOicSecPdAcl_get_resources, args); if (!jData || env->ExceptionCheck()) { return OC_STACK_ERROR; } - acl->resources[i] = (char*) env->GetStringUTFChars(jData, 0); + pdacl->resources[i] = (char*) env->GetStringUTFChars(jData, 0); } - jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecAcl_get_permission); + jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecPdAcl_get_permission); if (env->ExceptionCheck()) { return OC_STACK_ERROR; } - acl->permission = jCount; - jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecAcl_get_periods_cnt); + pdacl->permission = jCount; + jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecPdAcl_get_periods_cnt); if (env->ExceptionCheck()) { return OC_STACK_ERROR; } - acl->prdRecrLen = jCount; - acl->periods = new char*[jCount]; + 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_OcOicSecAcl_get_periods, args); + jData = (jstring) env->CallObjectMethodA(in, g_mid_OcOicSecPdAcl_get_periods, args); if (!jData || env->ExceptionCheck()) { return OC_STACK_ERROR; } - acl->periods[i] = (char*) env->GetStringUTFChars(jData, 0); + pdacl->periods[i] = (char*) env->GetStringUTFChars(jData, 0); } - acl->recurrences = new char*[jCount]; //TODO:Period Len and Reccurence len is same + 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_OcOicSecAcl_get_recurrences, args); + jData = (jstring) env->CallObjectMethodA(in, g_mid_OcOicSecPdAcl_get_recurrences, args); if (!jData || env->ExceptionCheck()) { return OC_STACK_ERROR; } - acl->recurrences[i] = (char*) env->GetStringUTFChars(jData, 0); - } - - jData = (jstring) env->CallObjectMethod(in, g_mid_OcOicSecAcl_get_rownerID); - if (!jData || env->ExceptionCheck()) - { - return OC_STACK_ERROR; - } - - str = (char*) env->GetStringUTFChars(jData, 0); - - if (OC_STACK_OK == ConvertStrToUuid(str, &acl->rownerID)) - { - env->ReleaseStringUTFChars(jData, str); - } - else - { - return OC_STACK_ERROR; + pdacl->recurrences[i] = (char*) env->GetStringUTFChars(jData, 0); } - return OC_STACK_OK; } diff --git a/android/android_api/base/jni/JniSecureUtils.h b/android/android_api/base/jni/JniSecureUtils.h index c239c445a..c16457de2 100644 --- a/android/android_api/base/jni/JniSecureUtils.h +++ b/android/android_api/base/jni/JniSecureUtils.h @@ -29,10 +29,12 @@ class JniSecureUtils static std::string convertUUIDtoStr(OicUuid_t uuid); static void convertStrToUUID(char *str, OicUuid_t &uuid); public: + static void FreeACLList(OicSecAcl_t *acl); static jobject convertProvisionresultVectorToJavaList(JNIEnv *, const OC::PMResultList_t *); static jobjectArray convertDeviceVectorToJavaArray(JNIEnv *env, 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); }; diff --git a/android/android_api/base/src/androidTest/java/org/iotivity/base/SmokeTest.java b/android/android_api/base/src/androidTest/java/org/iotivity/base/SmokeTest.java index 96453435e..4842ecae8 100644 --- a/android/android_api/base/src/androidTest/java/org/iotivity/base/SmokeTest.java +++ b/android/android_api/base/src/androidTest/java/org/iotivity/base/SmokeTest.java @@ -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 diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcDeviceInfo.java b/android/android_api/base/src/main/java/org/iotivity/base/OcDeviceInfo.java index 4a89856c2..062405f20 100644 --- a/android/android_api/base/src/main/java/org/iotivity/base/OcDeviceInfo.java +++ b/android/android_api/base/src/main/java/org/iotivity/base/OcDeviceInfo.java @@ -22,20 +22,27 @@ 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 index 000000000..aff323854 --- /dev/null +++ b/android/android_api/base/src/main/java/org/iotivity/base/OcDirectPairDevice.java @@ -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; + } +} diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcHeaderOption.java b/android/android_api/base/src/main/java/org/iotivity/base/OcHeaderOption.java index d672bf0ac..6bf442f50 100644 --- a/android/android_api/base/src/main/java/org/iotivity/base/OcHeaderOption.java +++ b/android/android_api/base/src/main/java/org/iotivity/base/OcHeaderOption.java @@ -30,19 +30,30 @@ import java.security.InvalidParameterException; * After creating instances of OcHeaderOptions, use setHeaderOptions API * (in OcResource) to set header Options. * NOTE: optionId is an integer value which MUST be within - * range of 2048 to 3000 inclusive of lower and upper bound. + * range of 2048 to 3000 inclusive of lower and upper bound + * except for a few options including If-Match with empty(num : 1), + * If-None-Match(num : 5), Location-Path(num : 8), + * Location-Query(num : 20) CoAP option. * HeaderOption instance creation fails if above condition is not satisfied. */ public class OcHeaderOption { public static final int MIN_HEADER_OPTION_ID = 2048; public static final int MAX_HEADER_OPTION_ID = 3000; + public static final int IF_MATCH_OPTION_ID = 1; + public static final int IF_NONE_MATCH_OPTION_ID = 5; + public static final int LOCATION_PATH_OPTION_ID = 8; + public static final int LOCATION_QUERY_OPTION_ID = 20; private int mOptionId; private String mOptionData; public OcHeaderOption(int optionId, String optionData) { - if (!(optionId >= MIN_HEADER_OPTION_ID && optionId <= MAX_HEADER_OPTION_ID)) { + if (!(optionId >= MIN_HEADER_OPTION_ID && optionId <= MAX_HEADER_OPTION_ID) + && optionId != IF_MATCH_OPTION_ID + && optionId != IF_NONE_MATCH_OPTION_ID + && optionId != LOCATION_PATH_OPTION_ID + && optionId != LOCATION_QUERY_OPTION_ID) { throw new InvalidParameterException("Option ID range is invalid"); } diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcPlatform.java b/android/android_api/base/src/main/java/org/iotivity/base/OcPlatform.java index c8678ff34..76cd649b9 100644 --- a/android/android_api/base/src/main/java/org/iotivity/base/OcPlatform.java +++ b/android/android_api/base/src/main/java/org/iotivity/base/OcPlatform.java @@ -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 index 000000000..2c2b37f9e --- /dev/null +++ b/android/android_api/base/src/main/java/org/iotivity/base/OcPrmType.java @@ -0,0 +1,58 @@ +/*
+ * //******************************************************************
+ * //
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // Licensed under the Apache License, Version 2.0 (the "License");
+ * // you may not use this file except in compliance with the License.
+ * // You may obtain a copy of the License at
+ * //
+ * // http://www.apache.org/licenses/LICENSE-2.0
+ * //
+ * // Unless required by applicable law or agreed to in writing, software
+ * // distributed under the License is distributed on an "AS IS" BASIS,
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * // See the License for the specific language governing permissions and
+ * // limitations under the License.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+/**
+ * @brief direct pairing Method Type.
+ * 0: not allowed
+ * 1: pre-configured pin
+ * 2: random pin
+ */
+package org.iotivity.base;
+
+public enum OcPrmType {
+ DP_INVALID (-1),
+ DP_NOT_ALLOWED (0),
+ DP_PRE_CONFIGURED (1 << 0),
+ DP_RANDOM_PIN (1 << 1);
+
+ private int value;
+
+ private OcPrmType(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return this.value;
+ }
+
+ public static OcPrmType convertOcPrmType(int value) {
+ switch (value)
+ {
+ case 0:
+ return OcPrmType.DP_NOT_ALLOWED;
+ case 1:
+ return OcPrmType.DP_PRE_CONFIGURED;
+ case 2:
+ return OcPrmType.DP_RANDOM_PIN;
+ }
+ return OcPrmType.DP_INVALID;
+ }
+}
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcSecureResource.java b/android/android_api/base/src/main/java/org/iotivity/base/OcSecureResource.java index 218b9e29e..b1daf6c69 100644 --- a/android/android_api/base/src/main/java/org/iotivity/base/OcSecureResource.java +++ b/android/android_api/base/src/main/java/org/iotivity/base/OcSecureResource.java @@ -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/OicSecAce.java b/android/android_api/base/src/main/java/org/iotivity/base/OicSecAce.java new file mode 100644 index 000000000..a5bd53f69 --- /dev/null +++ b/android/android_api/base/src/main/java/org/iotivity/base/OicSecAce.java @@ -0,0 +1,80 @@ +/* + ******************************************************************* + * + * 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; +public class OicSecAce { + private String subjectID; + private int permission; + private List<OicSecResr> resources; + private List<OicSecValidity> validities; + + public OicSecAce(String subjectID, int permission, + List<OicSecResr> resources, List<OicSecValidity> validities) { + super(); + this.subjectID = subjectID; + this.permission = permission; + this.resources = resources; + this.validities = validities; + } + + public String getSubjectID() { + return subjectID; + } + + public void setSubjectID(String subjectID) { + this.subjectID = subjectID; + } + + public int getPermission() { + return permission; + } + + public void setPermission(int permission) { + this.permission = permission; + } + + public List<OicSecResr> getResourcesList() { + return resources; + } + + public OicSecResr[] getResources() { + return resources.toArray(new OicSecResr[resources.size()]); + } + public void setResources(List<OicSecResr> resources) { + this.resources = resources; + } + + public List<OicSecValidity> getValiditiesList() { + return validities; + } + + public OicSecValidity[] getValidities() { + return validities.toArray(new OicSecValidity[validities.size()]); + } + + + public void setValidities(List<OicSecValidity> validities) { + this.validities = validities; + } +} diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OicSecAcl.java b/android/android_api/base/src/main/java/org/iotivity/base/OicSecAcl.java index a47ffaaf6..f0fdc72a3 100644 --- a/android/android_api/base/src/main/java/org/iotivity/base/OicSecAcl.java +++ b/android/android_api/base/src/main/java/org/iotivity/base/OicSecAcl.java @@ -1,116 +1,55 @@ -/* - * //****************************************************************** - * // - * // 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. - * // - * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - */ - -package org.iotivity.base; - -import java.io.Serializable; -import java.util.List; -import java.util.Arrays; - -public class OicSecAcl implements Serializable { - - private String subject; - private int permission; - private List<String> resources; - private List<String> periods; - private List<String> recurrences; - private String rownerID; - - public OicSecAcl(String subject, List<String> recurrences, List<String> periods, int permission, - List<String> resources, String rownerID) { - this.subject = subject; - this.recurrences = recurrences; - this.periods = periods; - this.permission = permission; - this.resources = resources; - this.rownerID = rownerID; - } - - public String getSubject() { - return this.subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - - public void setRownerID(String rownerID) { - this.rownerID = rownerID; - } - - public List<String> getRecurrences() { - return recurrences; - } - - public void setRecurrences(List<String> recurrences) { - this.recurrences = recurrences; - } - - public List<String> getPeriods() { - return periods; - } - - public void setPeriods(List<String> periods) { - this.periods = periods; - } - - public int getPermission() { - return this.permission; - } - - public void setPermission(int permission) { - this.permission = permission; - } - - public List<String> getResources() { - return resources; - } - - public void setResources(List<String> resources) { - this.resources = resources; - } - - public int getResourcesCount() { - return this.resources.size(); - } - - public String getResources(int i) { - return this.resources.get(i); - } - - public int getPeriodsCount() { - return this.periods.size(); - } - - public String getPeriods(int i) { - return this.periods.get(i); - } - - public String getRecurrences(int i) { - return this.recurrences.get(i); - } - - public String getRownerID() { - return this.rownerID; - } -} +/*
+ *******************************************************************
+ *
+ * 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;
+
+public class OicSecAcl {
+ private String rownerID;
+ private List<OicSecAce> oicSecAces;
+
+ public OicSecAcl (String rownerID, List<OicSecAce> oicSecAces) {
+ super();
+ this.rownerID = rownerID;
+ this.oicSecAces = oicSecAces;
+ }
+ public String getRownerID() {
+ return rownerID;
+ }
+
+ public void setRownerID(String rownerID) {
+ this.rownerID = rownerID;
+ }
+
+ public List<OicSecAce> getOicSecAcesList() {
+ return oicSecAces;
+ }
+
+ public OicSecAce[] getOicSecAces() {
+ return oicSecAces.toArray(new OicSecAce[oicSecAces.size()]);
+ }
+
+ public void setOicSecAces(List<OicSecAce> oicSecAces) {
+ this.oicSecAces = oicSecAces;
+ }
+}
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 index 000000000..576812320 --- /dev/null +++ b/android/android_api/base/src/main/java/org/iotivity/base/OicSecPdAcl.java @@ -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); + } +} diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OicSecResr.java b/android/android_api/base/src/main/java/org/iotivity/base/OicSecResr.java new file mode 100644 index 000000000..490462ebd --- /dev/null +++ b/android/android_api/base/src/main/java/org/iotivity/base/OicSecResr.java @@ -0,0 +1,102 @@ +/* + ******************************************************************* + * + * 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; +public class OicSecResr { + + private String href; + private String rel; + private List<String> types; + private int typeLen; + private List<String> interfaces; + private int interfaceLen; + + public OicSecResr(String href, String rel, List<String> types, int typeLen, + List<String> interfaces, int interfaceLen) { + super(); + this.href = href; + this.rel = rel; + this.types = types; + this.typeLen = typeLen; + this.interfaces = interfaces; + this.interfaceLen = interfaceLen; + } + + public String getHref() { + return href; + } + + public void setHref(String href) { + this.href = href; + } + + public String getRel() { + return rel; + } + + public void setRel(String rel) { + this.rel = rel; + } + + public List<String> getTypesList() { + return types; + } + + public void setTypes(List<String> types) { + this.types = types; + } + + public int getTypeLen() { + return typeLen; + } + + public void setTypeLen(int typeLen) { + this.typeLen = typeLen; + } + + public List<String> getInterfacesList() { + return interfaces; + } + + public String getInterfaces(int i) { + return this.interfaces.get(i); + } + + public String getTypes(int i) { + return this.types.get(i); + } + + public void setInterfaces(List<String> interfaces) { + this.interfaces = interfaces; + } + + public int getInterfaceLen() { + return interfaceLen; + } + + public void setInterfaceLen(int interfaceLen) { + this.interfaceLen = interfaceLen; + } + +} diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OicSecValidity.java b/android/android_api/base/src/main/java/org/iotivity/base/OicSecValidity.java new file mode 100644 index 000000000..0846658d0 --- /dev/null +++ b/android/android_api/base/src/main/java/org/iotivity/base/OicSecValidity.java @@ -0,0 +1,67 @@ +/* + ******************************************************************* + * + * 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; +public class OicSecValidity { + private String period; + private List<String> recurrences; + private int recurrenceLen; + + public OicSecValidity(String period, List<String> recurrences, + int recurrenceLen) { + super(); + this.period = period; + this.recurrences = recurrences; + this.recurrenceLen = recurrenceLen; + } + + public String getPeriod() { + return period; + } + + public void setPeriod(String period) { + this.period = period; + } + + public List<String> getRecurrencesList() { + return recurrences; + } + + public String getRecurrences(int i) { + return this.recurrences.get(i); + } + + public void setRecurrences(List<String> recurrences) { + this.recurrences = recurrences; + } + + public int getRecurrenceLen() { + return recurrenceLen; + } + + public void setRecurrenceLen(int recurrenceLen) { + this.recurrenceLen = recurrenceLen; + } + +} diff --git a/android/android_api/base/src/main/java/org/iotivity/ca/CaIpInterface.java b/android/android_api/base/src/main/java/org/iotivity/ca/CaIpInterface.java index 81ab7d569..2314df9ff 100644 --- a/android/android_api/base/src/main/java/org/iotivity/ca/CaIpInterface.java +++ b/android/android_api/base/src/main/java/org/iotivity/ca/CaIpInterface.java @@ -73,16 +73,16 @@ public class CaIpInterface { private static BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
- if (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
- WifiManager.WIFI_STATE_UNKNOWN) == WifiManager.WIFI_STATE_DISABLED) {
- caIpStateDisabled();
- } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
+ if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
ConnectivityManager manager = (ConnectivityManager)
mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo nwInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+ NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+ NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
- if(nwInfo.isConnected()) {
+ if (mobileInfo != null && mobileInfo.isConnected() || wifiInfo.isConnected()) {
caIpStateEnabled();
+ } else {
+ caIpStateDisabled();
}
}
diff --git a/android/android_api/base/src/main/java/org/iotivity/ca/CaLeClientInterface.java b/android/android_api/base/src/main/java/org/iotivity/ca/CaLeClientInterface.java index 0801bdbf4..8b383a7e5 100644 --- a/android/android_api/base/src/main/java/org/iotivity/ca/CaLeClientInterface.java +++ b/android/android_api/base/src/main/java/org/iotivity/ca/CaLeClientInterface.java @@ -41,7 +41,7 @@ import android.util.Log; public class CaLeClientInterface { private static String SERVICE_UUID = "ADE3D529-C784-4F63-A987-EB69F70EE816"; - private static String TAG = "Sample_Service : CaLeClientInterface"; + private static String TAG = "OIC_LE_CB_INTERFACE"; private static Context mContext; private CaLeClientInterface(Context context) { diff --git a/android/examples/DirectPairing/.classpath b/android/examples/DirectPairing/.classpath new file mode 100644 index 000000000..26bdfa6eb --- /dev/null +++ b/android/examples/DirectPairing/.classpath @@ -0,0 +1,9 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="src" path="gen"/>
+ <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
+ <classpathentry kind="output" path="bin/classes"/>
+</classpath>
diff --git a/android/examples/DirectPairing/.project b/android/examples/DirectPairing/.project new file mode 100644 index 000000000..2dadd4230 --- /dev/null +++ b/android/examples/DirectPairing/.project @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>Iot</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ApkBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/android/examples/DirectPairing/DirectPairing.iml b/android/examples/DirectPairing/DirectPairing.iml new file mode 100644 index 000000000..5de258aea --- /dev/null +++ b/android/examples/DirectPairing/DirectPairing.iml @@ -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 index 000000000..8499e31a0 --- /dev/null +++ b/android/examples/DirectPairing/build.gradle @@ -0,0 +1,38 @@ +apply plugin: 'com.android.application'
+
+android {
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
+
+ defaultConfig {
+ applicationId "org.iotivity.base.examples.DirectPairing"
+ minSdkVersion 21
+ targetSdkVersion 21
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../android_api/base/build/outputs/aar/"
+ }
+}
+
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
+}
+
diff --git a/android/examples/DirectPairing/project.properties b/android/examples/DirectPairing/project.properties new file mode 100644 index 000000000..8e02666b8 --- /dev/null +++ b/android/examples/DirectPairing/project.properties @@ -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 index 000000000..54ec6b9bf --- /dev/null +++ b/android/examples/DirectPairing/src/main/AndroidManifest.xml @@ -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 Binary files differnew file mode 100644 index 000000000..43b7a1c5c --- /dev/null +++ b/android/examples/DirectPairing/src/main/assets/oic_svr_db_client_directpairing.dat 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 index 000000000..377917c84 --- /dev/null +++ b/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/ExpandableListAdapter.java @@ -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 index 000000000..f44f97c26 --- /dev/null +++ b/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/Led.java @@ -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 index 000000000..90c43015e --- /dev/null +++ b/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/MainActivity.java @@ -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 index 000000000..c7934228a --- /dev/null +++ b/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/StringConstants.java @@ -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 Binary files differnew file mode 100644 index 000000000..2e69816bd --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_down.png 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 Binary files differnew file mode 100644 index 000000000..91667d5c7 --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_right.png 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 Binary files differnew file mode 100644 index 000000000..288b66551 --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/drawable-hdpi/ic_launcher.png 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 Binary files differnew file mode 100644 index 000000000..6ae570b4d --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/drawable-mdpi/ic_launcher.png 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 Binary files differnew file mode 100644 index 000000000..d4fb7cd9d --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/drawable-xhdpi/ic_launcher.png 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 Binary files differnew file mode 100644 index 000000000..85a608158 --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/drawable-xxhdpi/ic_launcher.png 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 index 000000000..1ee1a2bce --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/layout/activity_main.xml @@ -0,0 +1,95 @@ +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical"
+ android:paddingBottom="@dimen/activity_vertical_margin"
+ android:paddingLeft="@dimen/activity_horizontal_margin"
+ android:paddingRight="@dimen/activity_horizontal_margin"
+ android:paddingTop="@dimen/activity_vertical_margin"
+ tools:context="com.example.iot.MainActivity" >
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:weightSum="1" >
+
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_weight="0.75"
+ android:gravity="center"
+ android:text="@string/discover_items"
+ android:textSize="18sp" />
+
+ <Switch
+ android:id="@+id/discover"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_weight="0.25" />
+ </LinearLayout>
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="2dp"
+ android:background="#13AEF4" />
+
+ <ListView
+ android:id="@+id/list_view"
+ android:layout_width="match_parent"
+ android:layout_height="250dp" />
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="2dp"
+ android:background="#13AEF4" />
+
+ <RelativeLayout
+ android:id="@+id/relLay"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal"
+ android:padding="15dp" >
+
+ <Button
+ android:id="@+id/saveDiscovered"
+ android:layout_width="90dp"
+ android:layout_height="30dp"
+ android:layout_centerInParent="true"
+ android:background="#13AEF4"
+ android:text="Save"
+ android:textColor="#FFFFFF" />
+ </RelativeLayout>
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="2dp"
+ android:background="#13AEF4" />
+
+ <TextView
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_vertical"
+ android:paddingLeft="50dp"
+ android:text="@string/paired_list"
+ android:textSize="18sp" />
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="2dp"
+ android:background="#13AEF4" />
+
+ <ExpandableListView
+ android:id="@+id/list_view_paired_list"
+ android:layout_width="fill_parent"
+ android:layout_height="200dp"
+ android:paddingTop="5dp"
+ android:groupIndicator="@null" >
+ </ExpandableListView>
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="2dp"
+ android:background="#13AEF4" />
+
+</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 index 000000000..74874c5fd --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/layout/custom_list_view.xml @@ -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 index 000000000..95be91655 --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/layout/group_indicator.xml @@ -0,0 +1,6 @@ +<selector xmlns:android="http://schemas.android.com/apk/res/android">
+Â <item android:drawable="@drawable/arrow_right" android:state_empty="true"></item>
+Â Â Â Â <item android:drawable="@drawable/arrow_down" android:state_expanded="true"></item>
+Â Â Â Â <item android:drawable="@drawable/arrow_right"></item>
+
+</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 index 000000000..d4d9218ff --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/layout/list_group.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="fill_parent"
+ android:layout_height="40dp"
+ android:background="#ffffff"
+ android:orientation="horizontal" >
+
+ <TextView
+ android:id="@+id/title"
+ android:layout_width="wrap_content"
+ android:layout_height="40dp"
+ android:layout_weight="0.9"
+ android:gravity="center_vertical"
+ android:paddingLeft="40dp"
+ android:text="Items"
+ android:textColor="#040404"
+ android:textSize="16sp"
+ android:textStyle="bold"
+ android:typeface="sans" />
+
+ <ImageView
+ android:id="@+id/image"
+ android:layout_width="wrap_content"
+ android:layout_height="20dp"
+ android:layout_gravity="center_vertical"
+ android:layout_weight="0.1" />
+
+</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 index 000000000..6579c3611 --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/layout/list_item.xml @@ -0,0 +1,39 @@ +<?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="vertical" >
+
+ <TextView
+ android:id="@+id/textViewItem"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:gravity="center_vertical"
+ android:paddingLeft="50dp"
+ android:text="Paired Items"
+ android:textColor="#545454"
+ android:textSize="15sp" />
+
+ <TextView
+ android:id="@+id/textViewSource"
+ android:layout_below="@id/textViewItem"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:gravity="center_vertical"
+ android:paddingLeft="50dp"
+ android:text="Paired Source"
+ android:textColor="#545454"
+ android:textSize="15sp" />
+
+ <TextView
+ android:id="@+id/textViewStatus"
+ android:layout_below="@id/textViewSource"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:gravity="center_vertical"
+ android:paddingLeft="50dp"
+ android:text="Paired Status"
+ android:textColor="#545454"
+ android:textSize="15sp" />
+
+</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 index 000000000..3e5155b68 --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/menu/main.xml @@ -0,0 +1,11 @@ +<menu xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:app="http://schemas.android.com/apk/res-auto"
+ xmlns:tools="http://schemas.android.com/tools"
+ tools:context="org.iotivity.base.examples.MainActivity" >
+
+ <item
+ android:id="@+id/action_settings"
+ android:orderInCategory="100"
+ android:title="@string/action_settings"/>
+
+</menu>
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 index 000000000..0ce139665 --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/values-v11/styles.xml @@ -0,0 +1,11 @@ +<resources>
+
+ <!--
+ Base application theme for API 11+. This theme completely replaces + AppBaseTheme from res/values/styles.xml on API 11+ devices.
+ -->
+ <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
+ <!-- API 11 theme customizations can go here. -->
+ </style>
+
+</resources>
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 index 000000000..94dd245c9 --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/values-v14/styles.xml @@ -0,0 +1,12 @@ +<resources>
+
+ <!--
+ 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.
+ -->
+ <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
+ <!-- API 14 theme customizations can go here. -->
+ </style>
+
+</resources>
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 index 000000000..f9f069fde --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/values-w820dp/dimens.xml @@ -0,0 +1,10 @@ +<resources>
+
+ <!--
+ 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).
+ -->
+ <dimen name="activity_horizontal_margin">64dp</dimen>
+
+</resources>
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 index 000000000..2e0e2ae4b --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/values/dimens.xml @@ -0,0 +1,7 @@ +<resources>
+
+ <!-- Default screen margins, per the Android Design guidelines. -->
+ <dimen name="activity_horizontal_margin">16dp</dimen>
+ <dimen name="activity_vertical_margin">16dp</dimen>
+
+</resources>
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 index 000000000..0fe7671e9 --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/values/strings.xml @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources>
+
+ <string name="app_name">DirectPairingClient</string>
+ <string name="discover_items">Discover Resources</string> + <string name="paired_items">Paired Resources</string> + <string name="paired_list">Direct Paired Resources</string>
+ <string name="action_settings">Settings</string>
+
+</resources>
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 index 000000000..287aa963e --- /dev/null +++ b/android/examples/DirectPairing/src/main/res/values/styles.xml @@ -0,0 +1,20 @@ +<resources>
+
+ <!--
+ Base application theme, dependent on API level. This theme is replaced + by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
+ -->
+ <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
+ <!--
+ Theme customizations available in newer API levels can go in + res/values-vXX/styles.xml, while customizations related to + backward-compatibility can go here.
+ -->
+ </style>
+
+ <!-- Application theme. -->
+ <style name="AppTheme" parent="AppBaseTheme">
+ <!-- All customizations that are NOT specific to a particular API-level can go here. -->
+ </style>
+
+</resources>
diff --git a/android/examples/devicediscoveryclient/src/main/java/org/iotivity/base/examples/DeviceDiscoveryClient.java b/android/examples/devicediscoveryclient/src/main/java/org/iotivity/base/examples/DeviceDiscoveryClient.java index 309fc3b0c..60e3a5dce 100644 --- a/android/examples/devicediscoveryclient/src/main/java/org/iotivity/base/examples/DeviceDiscoveryClient.java +++ b/android/examples/devicediscoveryclient/src/main/java/org/iotivity/base/examples/DeviceDiscoveryClient.java @@ -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."); diff --git a/android/examples/devicediscoveryserver/src/main/java/org/iotivity/base/examples/DeviceDiscoveryServer.java b/android/examples/devicediscoveryserver/src/main/java/org/iotivity/base/examples/DeviceDiscoveryServer.java index b022f0ca0..3c2097283 100644 --- a/android/examples/devicediscoveryserver/src/main/java/org/iotivity/base/examples/DeviceDiscoveryServer.java +++ b/android/examples/devicediscoveryserver/src/main/java/org/iotivity/base/examples/DeviceDiscoveryServer.java @@ -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); diff --git a/android/examples/provisioningclient/src/main/assets/oic_svr_db_client.dat b/android/examples/provisioningclient/src/main/assets/oic_svr_db_client.dat Binary files differindex b8d249c3e..4b5b91881 100644 --- a/android/examples/provisioningclient/src/main/assets/oic_svr_db_client.dat +++ b/android/examples/provisioningclient/src/main/assets/oic_svr_db_client.dat diff --git a/android/examples/provisioningclient/src/main/assets/oic_svr_db_client.json b/android/examples/provisioningclient/src/main/assets/oic_svr_db_client.json index 22dfeba27..6471926fd 100644 --- a/android/examples/provisioningclient/src/main/assets/oic_svr_db_client.json +++ b/android/examples/provisioningclient/src/main/assets/oic_svr_db_client.json @@ -8,38 +8,36 @@ {
"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": ""
- },
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
+ }
+ ],
+ "permission": 2
+ },
+ {
+ "subjectuuid": "*",
+ "resources": [
{
- "href": "/oic/ad",
+ "href": "/oic/sec/doxm",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.doxm"],
+ "if": ["oic.if.baseline"]
},
{
- "href": "/oic/sec/amacl",
+ "href": "/oic/sec/pstat",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.pstat"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 2
@@ -48,27 +46,27 @@ "subjectuuid": "*",
"resources": [
{
- "href": "/oic/sec/doxm",
+ "href": "/oic/sec/pconf",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.pconf"],
+ "if": ["oic.if.baseline"]
},
{
- "href": "/oic/sec/pstat",
+ "href": "/oic/sec/dpairing",
"rel": "",
- "rt": "",
- "if": ""
- }
+ "rt": ["oic.r.dpairing"],
+ "if": ["oic.if.baseline"]
+ }
],
"permission": 2
}
]
},
"rowneruuid" : "61646D69-6E44-6576-6963-655575696430"
- },
+ },
"pstat": {
"isop": true,
- "cm": 2,
+ "cm": 0,
"tm": 0,
"om": 3,
"sm": 3,
@@ -81,7 +79,7 @@ "sct": 1,
"owned": true,
"deviceuuid": "61646D69-6E44-6576-6963-655575696430",
- "dpc": false,
+ "x.org.iotivity.dpc": false,
"devowneruuid": "61646D69-6E44-6576-6963-655575696430",
"rowneruuid": "61646D69-6E44-6576-6963-655575696430"
}
diff --git a/android/examples/provisioningclient/src/main/java/org/iotivity/base/examples/provisioningclient/ProvisioningClient.java b/android/examples/provisioningclient/src/main/java/org/iotivity/base/examples/provisioningclient/ProvisioningClient.java index fbd8eda01..b83410114 100644 --- a/android/examples/provisioningclient/src/main/java/org/iotivity/base/examples/provisioningclient/ProvisioningClient.java +++ b/android/examples/provisioningclient/src/main/java/org/iotivity/base/examples/provisioningclient/ProvisioningClient.java @@ -24,6 +24,11 @@ import org.iotivity.base.OcPlatform; import org.iotivity.base.OcProvisioning; import org.iotivity.base.OcSecureResource; import org.iotivity.base.OicSecAcl; +import org.iotivity.base.OicSecAce; +import org.iotivity.base.OicSecResr; +import org.iotivity.base.OicSecValidity; +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; @@ -41,29 +46,51 @@ import java.util.EnumSet; import java.util.List; public class ProvisioningClient extends Activity implements - OcSecureResource.DoOwnershipTransferListener, OcSecureResource.ProvisionPairwiseDevicesListener { +OcSecureResource.DoOwnershipTransferListener, OcSecureResource.ProvisionPairwiseDevicesListener { private static final String TAG = "Provisioning Client: "; private static final int BUFFER_SIZE = 1024; int unownedDevCount = StringConstants.NUMBER_ZERO; OcProvisioning.PinCallbackListener pinCallbackListener = - new OcProvisioning.PinCallbackListener() { - @Override + new OcProvisioning.PinCallbackListener() { + @Override public String pinCallbackListener() { Log.d(TAG, "Inside Pin Callback "); return ""; } - }; + }; private String filePath = ""; private OcSecureResource newSecureResource; 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()); + if (ownedDeviceList.size() == 1) { + new ProvisionACLAsyncTask().execute(); + } + if (ownedDeviceList.size() > 1) { + new GetLinkedDevicesAsyncTask().execute(); + } + } + } + }; + OcSecureResource.ProvisionAclListener provisionAclListener = - new OcSecureResource.ProvisionAclListener() { - @Override + new OcSecureResource.ProvisionAclListener() { + @Override public void provisionAclListener(List<ProvisionResult> provisionResults, - int hasError) { + int hasError) { Log.d(TAG, "Inside ProvisionAclListener "); if (hasError == StringConstants.ERROR_CODE) { logMessage("Error: ACL Provision failed !!"); @@ -72,12 +99,12 @@ public class ProvisioningClient extends Activity implements new DeviceRevocationAsyncTask().execute(); } } - }; + }; OcSecureResource.ProvisionCredentialsListener provisionCredentialsListener = - new OcSecureResource.ProvisionCredentialsListener() { - @Override + new OcSecureResource.ProvisionCredentialsListener() { + @Override public void provisionCredentialsListener(List<ProvisionResult> provisionResults, - int hasError) { + int hasError) { Log.d(TAG, "Inside ProvisionCredentialsListener "); if (hasError == StringConstants.ERROR_CODE) { logMessage("Error: Provision Credentials failed !!"); @@ -86,12 +113,12 @@ public class ProvisioningClient extends Activity implements new ProvisionACLAsyncTask().execute(); } } - }; + }; OcSecureResource.UnlinkDevicesListener unlinkDevicesListener = - new OcSecureResource.UnlinkDevicesListener() { - @Override + new OcSecureResource.UnlinkDevicesListener() { + @Override public void unlinkDevicesListener(List<ProvisionResult> provisionResults, - int hasError) { + int hasError) { Log.d(TAG, "Inside unlinkDevicesListener "); if (hasError == StringConstants.ERROR_CODE) { logMessage("Error: UnLinking device !!"); @@ -100,43 +127,43 @@ public class ProvisioningClient extends Activity implements new ProvisionCredentialAsyncTask().execute(); } } - }; + }; OcSecureResource.RemoveDeviceListener removeDeviceListener = - new OcSecureResource.RemoveDeviceListener() { - @Override + new OcSecureResource.RemoveDeviceListener() { + @Override public void removeDeviceListener(List<ProvisionResult> provisionResults, - int hasError) { + int hasError) { if (hasError == StringConstants.ERROR_CODE) { logMessage("Error: Remove Fail !!"); } else { logMessage("Remove Device done !!"); } } - }; + }; @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_secure_provision_client); - mEventsTextView = new TextView(this); - mEventsTextView.setGravity(Gravity.BOTTOM); - mEventsTextView.setMovementMethod(new ScrollingMovementMethod()); - LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout); - layout.addView(mEventsTextView, new LinearLayout.LayoutParams( + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_secure_provision_client); + mEventsTextView = new TextView(this); + mEventsTextView.setGravity(Gravity.BOTTOM); + mEventsTextView.setMovementMethod(new ScrollingMovementMethod()); + LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout); + layout.addView(mEventsTextView, new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f) - ); - 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(); + ); + 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(); } - initOICStack(); - } /** * configure OIC platform and call findResource @@ -156,7 +183,7 @@ public class ProvisioningClient extends Activity implements * Initialize DataBase */ String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") + - File.separator; + File.separator; File file = new File(sqlDbPath); //check files directory exists if (!(file.isDirectory())) { @@ -173,37 +200,97 @@ public class ProvisioningClient extends Activity implements } @Override - synchronized public void doOwnershipTransferListener(List<ProvisionResult> ProvisionResultList, - int hasError) { - ProvisionResult pResult = ProvisionResultList.get(0); - if (hasError == StringConstants.ERROR_CODE) { - logMessage(TAG + "Ownership Transfer Failed for " + pResult.getDevId()); - } else { - logMessage(TAG + "Ownership Transfer Successful for " - + pResult.getDevId()); - unownedDevCount--; + synchronized public void doOwnershipTransferListener(List<ProvisionResult> ProvisionResultList, + int hasError) { + ProvisionResult pResult = ProvisionResultList.get(0); + if (hasError == StringConstants.ERROR_CODE) { + logMessage(TAG + "Ownership Transfer Failed for " + pResult.getDevId()); + } else { + logMessage(TAG + "Ownership Transfer Successful for " + + pResult.getDevId()); + unownedDevCount--; + } + if (unownedDevCount == 0) { //When done with Ownership Transfer + new OwnedDiscoveryAsyncTask().execute(); + } } - if (unownedDevCount == 0) { //When done with Ownership Transfer - new OwnedDiscoveryAsyncTask().execute(); + + + 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() + " and " + ownedDeviceList.get(1).getDeviceID()); newSecureResource = ownedDeviceList.get(0); - OcSecureResource newSecureResource2 = ownedDeviceList.get(1); - List<String> resources = new ArrayList<String>(); - List<String> periods = new ArrayList<String>(); + + List<OicSecResr> resources1 = new ArrayList<OicSecResr>(); + List<OicSecResr> resources2 = new ArrayList<OicSecResr>(); + List<OicSecValidity> validities = new ArrayList<OicSecValidity>(); + + List<String> types1 = new ArrayList<String>(); + types1.add(StringConstants.RESOURCE_TYPE_1A); + types1.add(StringConstants.RESOURCE_TYPE_1B); + List<String> types2 = new ArrayList<String>(); + types2.add(StringConstants.RESOURCE_TYPE_2A); + types2.add(StringConstants.RESOURCE_TYPE_2B); + List<String> interfaces = new ArrayList<String>(); + interfaces.add(StringConstants.RESOURCE_INTERFACE_1); + interfaces.add(StringConstants.RESOURCE_INTERFACE_2); + + OicSecResr oicSecResr1a = new OicSecResr(StringConstants.HREF_RESOURCES_1A, "", types1, 2, interfaces, 2); + OicSecResr oicSecResr1b = new OicSecResr(StringConstants.HREF_RESOURCES_1B, "", types1, 2, interfaces, 2); + resources1.add(oicSecResr1a); + resources1.add(oicSecResr1b); + + OicSecResr oicSecResr2a = new OicSecResr(StringConstants.HREF_RESOURCES_2A, "", types2, 2, interfaces, 2); + OicSecResr oicSecResr2b = new OicSecResr(StringConstants.HREF_RESOURCES_2B, "", types2, 2, interfaces, 2); + resources2.add(oicSecResr2a); + resources2.add(oicSecResr2b); + List<String> recurrences = new ArrayList<String>(); - recurrences.add(StringConstants.DEFAULT_RECURRENCES); - resources.add(StringConstants.DEFAULT_RESOURCES); - periods.add(StringConstants.DEFAULT_PERIOD); - OicSecAcl acl1 = new OicSecAcl(newSecureResource.getDeviceID(), recurrences, periods, - StringConstants.DEFAULT_PERMISSION, resources, StringConstants.DEFAULT_ROWNER_ID); - OicSecAcl acl2 = new OicSecAcl(newSecureResource2.getDeviceID(), recurrences, periods, - StringConstants.DEFAULT_PERMISSION, resources, StringConstants.DEFAULT_ROWNER_ID); + recurrences.add(StringConstants.DEFAULT_RECURRENCES_1); + recurrences.add(StringConstants.DEFAULT_RECURRENCES_2); + OicSecValidity oicSecValidity = new OicSecValidity(StringConstants.DEFAULT_PERIOD, + recurrences, 2); + validities.add(oicSecValidity); + + OicSecAce oicsecace1 = new OicSecAce(newSecureResource.getDeviceID(), + StringConstants.DEFAULT_PERMISSION, resources1, validities); + OcSecureResource newSecureResource2 = ownedDeviceList.get(1); + OicSecAce oicsecace2 = new OicSecAce(newSecureResource2.getDeviceID(), + StringConstants.DEFAULT_PERMISSION, resources2, validities); + + List<OicSecAce> oicSecAces1=new ArrayList<OicSecAce>(); + oicSecAces1.add(oicsecace1); + List<OicSecAce> oicSecAces2=new ArrayList<OicSecAce>(); + oicSecAces2.add(oicsecace2); + OicSecAcl acl1 = new OicSecAcl(StringConstants.DEFAULT_ROWNER_ID,oicSecAces1); + OicSecAcl acl2 = new OicSecAcl(StringConstants.DEFAULT_ROWNER_ID,oicSecAces2); + newSecureResource.provisionPairwiseDevices(EnumSet.of(CredType.SYMMETRIC_PAIR_WISE_KEY), KeySize.OWNER_PSK_LENGTH_128, acl1, newSecureResource2, acl2, this); } catch (Exception e) { @@ -213,19 +300,19 @@ public class ProvisioningClient extends Activity implements } @Override - public void provisionPairwiseDevicesListener(List<ProvisionResult> ProvisionResultList, - int hasError) { - if (hasError == StringConstants.ERROR_CODE) { - logMessage(TAG + "provisionPairwiseDevices Failed"); - } else { - for (int i = 0; i < ProvisionResultList.size(); i++) { - ProvisionResult pResult = ProvisionResultList.get(i); - logMessage(TAG + "provisionPairwiseDevices Result for " - + pResult.getDevId() + "is " + pResult.getResult()); - } - new GetLinkedDevicesAsyncTask().execute(); + public void provisionPairwiseDevicesListener(List<ProvisionResult> ProvisionResultList, + int hasError) { + if (hasError == StringConstants.ERROR_CODE) { + logMessage(TAG + "provisionPairwiseDevices Failed"); + } else { + for (int i = 0; i < ProvisionResultList.size(); i++) { + ProvisionResult pResult = ProvisionResultList.get(i); + logMessage(TAG + "provisionPairwiseDevices Result for " + + pResult.getDevId() + "is " + pResult.getResult()); + } + doDPProvisioning(); + } } - } /** * Copy svr db CBOR dat file from assets folder to app data files dir @@ -279,13 +366,13 @@ public class ProvisioningClient extends Activity implements public void logMsg(final String text) { runOnUiThread(new Runnable() { - public void run() { + public void run() { Message msg = new Message(); msg.obj = text; mEventsTextView.append(text); mEventsTextView.append("\n\n"); - } - }); + } + }); Log.i(TAG, text); Intent intent = new Intent(getPackageName()); intent.putExtra(StringConstants.MESSAGE, text); @@ -295,283 +382,323 @@ public class ProvisioningClient extends Activity implements private class DiscoveryOTTransferAsyncTask extends AsyncTask<Void, String, String> { @Override - protected void onPreExecute() { - super.onPreExecute(); - } + protected void onPreExecute() { + super.onPreExecute(); + } @Override - protected String doInBackground(Void... params) { - try { - /** - * Discover Un-owned devices - */ - publishProgress(TAG + "Discovering Unowned Devices"); - deviceList = new ArrayList<OcSecureResource>(OcProvisioning.discoverUnownedDevices - (StringConstants.DISCOVERY_TIMEOUT_10)); - if (deviceList.size() > 0) { - unownedDevCount = deviceList.size(); - for (int i = 0; i < deviceList.size(); i++) { - publishProgress(TAG + "Un-owned Discovered Device " + (i + 1) + "= " + - deviceList.get(i).getDeviceID()); - } - try { - OcProvisioning.SetownershipTransferCBdata(OxmType.OIC_JUST_WORKS, - pinCallbackListener); + protected String doInBackground(Void... params) { + try { + /** + * Discover Un-owned devices + */ + publishProgress(TAG + "Discovering Unowned Devices"); + deviceList = new ArrayList<OcSecureResource>(OcProvisioning.discoverUnownedDevices + (StringConstants.DISCOVERY_TIMEOUT_10)); + if (deviceList.size() > 0) { + unownedDevCount = deviceList.size(); for (int i = 0; i < deviceList.size(); i++) { - publishProgress(TAG + "Doing Ownership Transfer for " + + publishProgress(TAG + "Un-owned Discovered Device " + (i + 1) + "= " + deviceList.get(i).getDeviceID()); - deviceList.get(i).doOwnershipTransfer(ProvisioningClient.this); } - } catch (OcException e) { - publishProgress(TAG + "Ownership Transfer error: " + e.getMessage()); - return "Ownership Transfer error: " + e.getMessage(); + try { + OcProvisioning.SetownershipTransferCBdata(OxmType.OIC_JUST_WORKS, + pinCallbackListener); + for (int i = 0; i < deviceList.size(); i++) { + publishProgress(TAG + "Doing Ownership Transfer for " + + deviceList.get(i).getDeviceID()); + deviceList.get(i).doOwnershipTransfer(ProvisioningClient.this); + } + } catch (OcException e) { + publishProgress(TAG + "Ownership Transfer error: " + e.getMessage()); + return "Ownership Transfer error: " + e.getMessage(); + } + } else { + publishProgress(TAG + "No un-owned devices present"); + new OwnedDiscoveryAsyncTask().execute(); } - } else { - publishProgress(TAG + "No un-owned devices present"); - new OwnedDiscoveryAsyncTask().execute(); + } catch (OcException e) { + publishProgress(TAG + "Un-owned discovery error: " + e.getMessage()); + return "Un-owned discovery error: " + e.getMessage(); } - } catch (OcException e) { - publishProgress(TAG + "Un-owned discovery error: " + e.getMessage()); - return "Un-owned discovery error: " + e.getMessage(); + return "success"; } - return "success"; - } @Override - protected void onProgressUpdate(String... values) { - logMessage(values[0]); - } + protected void onProgressUpdate(String... values) { + logMessage(values[0]); + } @Override - protected void onPostExecute(String s) { - super.onPostExecute(s); - } + protected void onPostExecute(String s) { + super.onPostExecute(s); + } } private class ProvisionACLAsyncTask extends AsyncTask<Void, String, Void> { @Override - protected void onPreExecute() { - super.onPreExecute(); - } + protected void onPreExecute() { + super.onPreExecute(); + } @Override - protected Void doInBackground(Void... params) { - try { - if (ownedDeviceList.size() > 1) { - OcSecureResource ocSecureResource = ownedDeviceList.get(0); - OcSecureResource ocSecureResourceDest = ownedDeviceList.get(1); - publishProgress(TAG + "ACL Provision for " + ocSecureResource.getDeviceID()); - List<String> resources = new ArrayList<String>(); - List<String> periods = new ArrayList<String>(); - List<String> recurrences = new ArrayList<String>(); - recurrences.add(StringConstants.DEFAULT_RECURRENCES); - resources.add(StringConstants.DEFAULT_RESOURCES); - periods.add(StringConstants.DEFAULT_PERIOD); - OicSecAcl aclObject = new OicSecAcl(ocSecureResourceDest.getDeviceID(), - recurrences, periods, StringConstants.DEFAULT_PERMISSION, resources, - StringConstants.DEFAULT_ROWNER_ID); - ocSecureResource.provisionACL(aclObject, provisionAclListener); - } else { - publishProgress(TAG + "No Owned devices present"); + protected Void doInBackground(Void... params) { + try { + if (ownedDeviceList.size() > 0) { + OcSecureResource ocSecureResource = ownedDeviceList.get(0); + + publishProgress(TAG + "ACL Provision for " + ocSecureResource.getDeviceID()); + List<OicSecResr> resources1 = new ArrayList<OicSecResr>(); + List<OicSecResr> resources2 = new ArrayList<OicSecResr>(); + List<OicSecValidity> validities = new ArrayList<OicSecValidity>(); + + List<String> types1 = new ArrayList<String>(); + types1.add(StringConstants.RESOURCE_TYPE_1A); + types1.add(StringConstants.RESOURCE_TYPE_1B); + List<String> types2 = new ArrayList<String>(); + types2.add(StringConstants.RESOURCE_TYPE_2A); + types2.add(StringConstants.RESOURCE_TYPE_2B); + List<String> interfaces = new ArrayList<String>(); + interfaces.add(StringConstants.RESOURCE_INTERFACE_1); + interfaces.add(StringConstants.RESOURCE_INTERFACE_2); + + OicSecResr oicSecResr1a = new OicSecResr(StringConstants.HREF_RESOURCES_1A, "", types1, 2, interfaces, 2); + OicSecResr oicSecResr1b = new OicSecResr(StringConstants.HREF_RESOURCES_1B, "", types1, 2, interfaces, 2); + resources1.add(oicSecResr1a); + resources1.add(oicSecResr1b); + + OicSecResr oicSecResr2a = new OicSecResr(StringConstants.HREF_RESOURCES_2A, "", types2, 2, interfaces, 2); + OicSecResr oicSecResr2b = new OicSecResr(StringConstants.HREF_RESOURCES_2B, "", types2, 2, interfaces, 2); + resources2.add(oicSecResr2a); + resources2.add(oicSecResr2b); + + List<String> recurrences = new ArrayList<String>(); + recurrences.add(StringConstants.DEFAULT_RECURRENCES_1); + recurrences.add(StringConstants.DEFAULT_RECURRENCES_2); + OicSecValidity oicSecValidity = new OicSecValidity(StringConstants.DEFAULT_PERIOD, + recurrences, 2); + validities.add(oicSecValidity); + + OicSecAce oicsecace1 = new OicSecAce(StringConstants.DEFAULT_SUBJECT_ID1, + StringConstants.DEFAULT_PERMISSION, resources1, validities); + + OicSecAce oicsecace2 = new OicSecAce(StringConstants.DEFAULT_SUBJECT_ID2, + StringConstants.DEFAULT_PERMISSION, resources2, validities); + + List<OicSecAce> oicSecAces=new ArrayList<OicSecAce>(); + oicSecAces.add(oicsecace1); + oicSecAces.add(oicsecace2); + + OicSecAcl aclObject = new OicSecAcl(StringConstants.DEFAULT_ROWNER_ID, oicSecAces); + + ocSecureResource.provisionACL(aclObject, provisionAclListener); + } else { + publishProgress(TAG + "No Owned devices present"); + } + } catch (Exception e) { + publishProgress(TAG + "ProvisionACL error: " + e.getMessage()); } - } catch (Exception e) { - publishProgress(TAG + "ProvisionACL error: " + e.getMessage()); + return null; } - return null; - } @Override - protected void onProgressUpdate(String... values) { - logMessage(values[0]); - } + protected void onProgressUpdate(String... values) { + logMessage(values[0]); + } } private class ProvisionCredentialAsyncTask extends AsyncTask<Void, String, Void> { @Override - protected void onPreExecute() { - super.onPreExecute(); - } + protected void onPreExecute() { + super.onPreExecute(); + } @Override - protected Void doInBackground(Void... params) { - try { - if (ownedDeviceList.size() > 1) { - OcSecureResource ocSecureResource = ownedDeviceList.get(0); - OcSecureResource ocSecureResourceDest = ownedDeviceList.get(1); - publishProgress(TAG + "ProvisionCredential for " + - ocSecureResource.getDeviceID() + " with " + - ocSecureResourceDest.getDeviceID()); - ocSecureResource.provisionCredentials(EnumSet.of(CredType.SYMMETRIC_PAIR_WISE_KEY), - KeySize.OWNER_PSK_LENGTH_128, - ocSecureResourceDest, provisionCredentialsListener); - } else { - publishProgress(TAG + "Cannot perform credentials between devices"); + protected Void doInBackground(Void... params) { + try { + if (ownedDeviceList.size() > 1) { + OcSecureResource ocSecureResource = ownedDeviceList.get(0); + OcSecureResource ocSecureResourceDest = ownedDeviceList.get(1); + publishProgress(TAG + "ProvisionCredential for " + + ocSecureResource.getDeviceID() + " with " + + ocSecureResourceDest.getDeviceID()); + ocSecureResource.provisionCredentials(EnumSet.of(CredType.SYMMETRIC_PAIR_WISE_KEY), + KeySize.OWNER_PSK_LENGTH_128, + ocSecureResourceDest, provisionCredentialsListener); + } else { + publishProgress(TAG + "Cannot perform credentials between devices"); + } + } catch (Exception e) { + publishProgress(TAG + "Provision credentials error: " + e.getMessage()); } - } catch (Exception e) { - publishProgress(TAG + "Provision credentials error: " + e.getMessage()); + return null; } - return null; - } @Override - protected void onProgressUpdate(String... values) { - logMessage(values[0]); - } + protected void onProgressUpdate(String... values) { + logMessage(values[0]); + } } private class GetLinkedDevicesAsyncTask extends AsyncTask<Void, String, String> { @Override - protected void onPreExecute() { - super.onPreExecute(); - } + protected void onPreExecute() { + super.onPreExecute(); + } @Override - protected String doInBackground(Void... params) { - try { - if (ownedDeviceList.size() > 1) { - OcSecureResource ocSecureResource = ownedDeviceList.get(0); - publishProgress(TAG + "Get linked devices of " + ocSecureResource.getDeviceID()); - List<String> linkedDevices = ocSecureResource.getLinkedDevices(); - if (linkedDevices.size() > 0) { - for (int i = 0; i < linkedDevices.size(); i++) { - publishProgress(TAG + "Linked Devices " + - (i + 1) + "= " + linkedDevices.get(i)); + protected String doInBackground(Void... params) { + try { + if (ownedDeviceList.size() > 1) { + OcSecureResource ocSecureResource = ownedDeviceList.get(0); + publishProgress(TAG + "Get linked devices of " + ocSecureResource.getDeviceID()); + List<String> linkedDevices = ocSecureResource.getLinkedDevices(); + if (linkedDevices.size() > 0) { + for (int i = 0; i < linkedDevices.size(); i++) { + publishProgress(TAG + "Linked Devices " + + (i + 1) + "= " + linkedDevices.get(i)); + } + } else { + publishProgress(TAG + "No linked Devices found"); } } else { - publishProgress(TAG + "No linked Devices found"); + publishProgress(TAG + "Cannot perform linked devices"); } - } else { - publishProgress(TAG + "Cannot perform linked devices"); + } catch (Exception e) { + publishProgress(TAG + "getLinked device error: " + e.getMessage()); + return "failed"; } - } catch (Exception e) { - publishProgress(TAG + "getLinked device error: " + e.getMessage()); - return "failed"; + return "success"; } - return "success"; - } @Override - protected void onProgressUpdate(String... values) { - logMessage(values[0]); - } + protected void onProgressUpdate(String... values) { + logMessage(values[0]); + } @Override - protected void onPostExecute(String s) { - if ("success".equals(s)) { - new ProvisionUnlinkAsyncTask().execute(); + protected void onPostExecute(String s) { + if ("success".equals(s)) { + new ProvisionUnlinkAsyncTask().execute(); + } } - } } private class ProvisionUnlinkAsyncTask extends AsyncTask<Void, String, Void> { @Override - protected void onPreExecute() { - super.onPreExecute(); - } + protected void onPreExecute() { + super.onPreExecute(); + } @Override - protected Void doInBackground(Void... params) { - try { - if (ownedDeviceList.size() > 1) { - OcSecureResource ocSecureResource = ownedDeviceList.get(0); - OcSecureResource ocSecureResourceDest = ownedDeviceList.get(1); - publishProgress(TAG + "Un linking " + ocSecureResource.getDeviceID() + - " with " + ocSecureResourceDest.getDeviceID()); - ocSecureResource.unlinkDevices(ocSecureResourceDest, unlinkDevicesListener); - } else { - publishProgress(TAG + "Cannot perform unlink devices"); + protected Void doInBackground(Void... params) { + try { + if (ownedDeviceList.size() > 1) { + OcSecureResource ocSecureResource = ownedDeviceList.get(0); + OcSecureResource ocSecureResourceDest = ownedDeviceList.get(1); + publishProgress(TAG + "Un linking " + ocSecureResource.getDeviceID() + + " with " + ocSecureResourceDest.getDeviceID()); + ocSecureResource.unlinkDevices(ocSecureResourceDest, unlinkDevicesListener); + } else { + publishProgress(TAG + "Cannot perform unlink devices"); + } + } catch (Exception e) { + publishProgress(TAG + "Unlink error: " + e.getMessage()); } - } catch (Exception e) { - publishProgress(TAG + "Unlink error: " + e.getMessage()); + return null; } - return null; - } @Override - protected void onProgressUpdate(String... values) { - logMessage(values[0]); - } + protected void onProgressUpdate(String... values) { + logMessage(values[0]); + } } private class DeviceRevocationAsyncTask extends AsyncTask<Void, String, Void> { @Override - protected void onPreExecute() { - super.onPreExecute(); - } + protected void onPreExecute() { + super.onPreExecute(); + } @Override - protected Void doInBackground(Void... params) { - try { - if (ownedDeviceList.size() > 0) { - OcSecureResource ocSecureResource = ownedDeviceList.get(0); - publishProgress(TAG + "Removing " + ocSecureResource.getDeviceID()); - ocSecureResource.removeDevice(StringConstants.DISCOVERY_TIMEOUT_20, - removeDeviceListener); - } else { - publishProgress(TAG + "Cannot remove"); + protected Void doInBackground(Void... params) { + try { + if (ownedDeviceList.size() > 0) { + OcSecureResource ocSecureResource = ownedDeviceList.get(0); + publishProgress(TAG + "Removing " + ocSecureResource.getDeviceID()); + ocSecureResource.removeDevice(StringConstants.DISCOVERY_TIMEOUT_20, + removeDeviceListener); + } else { + publishProgress(TAG + "Cannot remove"); + } + } catch (Exception e) { + publishProgress(TAG + "Remove Device error: " + e.getMessage()); } - } catch (Exception e) { - publishProgress(TAG + "Remove Device error: " + e.getMessage()); + return null; } - return null; - } @Override - protected void onProgressUpdate(String... values) { - logMessage(values[0]); - } + protected void onProgressUpdate(String... values) { + logMessage(values[0]); + } } private class OwnedDiscoveryAsyncTask extends AsyncTask<Void, String, String> { @Override - protected void onPreExecute() { - super.onPreExecute(); - } + protected void onPreExecute() { + super.onPreExecute(); + } @Override - protected String doInBackground(Void... params) { - try { - publishProgress(TAG + "Initiate Owned device Discovery"); - ownedDeviceList = OcProvisioning.discoverOwnedDevices + protected String doInBackground(Void... params) { + try { + publishProgress(TAG + "Initiate Owned device Discovery"); + ownedDeviceList = OcProvisioning.discoverOwnedDevices (StringConstants.DISCOVERY_TIMEOUT_10); - 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") - ); + 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") + ); + } + } else { + publishProgress(TAG + "No Owned devices present"); } - } else { - publishProgress(TAG + "No Owned devices present"); + } catch (OcException e) { + publishProgress(TAG + "Owned device Discovery error: " + e.getMessage()); + return "Owned device Discovery error: " + e.getMessage(); } - } catch (OcException e) { - publishProgress(TAG + "Owned device Discovery error: " + e.getMessage()); - return "Owned device Discovery error: " + e.getMessage(); + return "success"; } - return "success"; - } @Override - protected void onProgressUpdate(String... values) { - logMessage(values[0]); - } + protected void onProgressUpdate(String... values) { + logMessage(values[0]); + } @Override - protected void onPostExecute(String s) { - if (ownedDeviceList.size() > 1 && "success".equals(s)) { - doPairwiseProvisioning(); + protected void onPostExecute(String s) { + + + if (ownedDeviceList.size() == 1 && "success".equals(s)) { + doDPProvisioning(); + } + if (ownedDeviceList.size() > 1 && "success".equals(s)) { + doPairwiseProvisioning(); + } + } - } } /** @@ -579,9 +706,9 @@ public class ProvisioningClient extends Activity implements */ public class MessageReceiver extends BroadcastReceiver { @Override - public void onReceive(Context context, Intent intent) { - final String message = intent.getStringExtra(StringConstants.MESSAGE); - logMessage(message); - } + public void onReceive(Context context, Intent intent) { + final String message = intent.getStringExtra(StringConstants.MESSAGE); + logMessage(message); + } } } diff --git a/android/examples/provisioningclient/src/main/java/org/iotivity/base/examples/provisioningclient/StringConstants.java b/android/examples/provisioningclient/src/main/java/org/iotivity/base/examples/provisioningclient/StringConstants.java index eb3a1892c..ec996167f 100644 --- a/android/examples/provisioningclient/src/main/java/org/iotivity/base/examples/provisioningclient/StringConstants.java +++ b/android/examples/provisioningclient/src/main/java/org/iotivity/base/examples/provisioningclient/StringConstants.java @@ -8,7 +8,25 @@ public interface StringConstants { public static final int ERROR_CODE = 1; 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 HREF_RESOURCES_1A = "/a/device1a"; + public static final String HREF_RESOURCES_1B = "/a/device1b"; + public static final String HREF_RESOURCES_2A = "/a/device2a"; + public static final String HREF_RESOURCES_2B = "/a/device2b"; + public static final String RESOURCE_TYPE_1A = "oic.wk.dev1a"; + public static final String RESOURCE_TYPE_1B = "oic.wk.dev1b"; + public static final String RESOURCE_TYPE_2A = "oic.wk.dev2a"; + public static final String RESOURCE_TYPE_2B = "oic.wk.dev2b"; + + + public static final String DEFAULT_SUBJECT_ID1 = "44446d69-6e44-6576-6963-655555494430"; + public static final String DEFAULT_SUBJECT_ID2 = "55556d69-6e44-6576-6963-655555494430"; + + public static final String RESOURCE_INTERFACE_1 = "oic.if.baseline"; + public static final String RESOURCE_INTERFACE_2 = "oic.if.r"; + + + public static final String DEFAULT_RECURRENCES_1 = "Daily"; + public static final String DEFAULT_RECURRENCES_2 = "Weekly"; public static final String DEFAULT_PERIOD = "12-12-16"; public static final int DEFAULT_PERMISSION = 31; public static final String OIC_CLIENT_CBOR_DB_FILE = "oic_svr_db_client.dat"; diff --git a/android/examples/settings.gradle b/android/examples/settings.gradle index 5a0364ce3..f9bd91e15 100755 --- a/android/examples/settings.gradle +++ b/android/examples/settings.gradle @@ -1,5 +1,5 @@ include ':simpleserver', ':simpleclient', ':fridgeserver', ':fridgeclient', ':guiclient', ':presenceserver', ':presenceclient', ':devicediscoveryclient', ':devicediscoveryserver', ':groupclient', ':groupserver', ':fridgegroupclient', ':fridgegroupserver' SECURED=System.getProperty('SECURE') if(SECURED== "1"){ - include ':provisioningclient' + include ':provisioningclient', ':DirectPairing' } diff --git a/android/examples/simpleclient/src/main/assets/oic_svr_db_client.dat b/android/examples/simpleclient/src/main/assets/oic_svr_db_client.dat Binary files differindex 9de47b806..13a3935c3 100644 --- a/android/examples/simpleclient/src/main/assets/oic_svr_db_client.dat +++ b/android/examples/simpleclient/src/main/assets/oic_svr_db_client.dat diff --git a/android/examples/simpleclient/src/main/assets/oic_svr_db_client.json b/android/examples/simpleclient/src/main/assets/oic_svr_db_client.json index 5052bd118..28323b5bf 100644 --- a/android/examples/simpleclient/src/main/assets/oic_svr_db_client.json +++ b/android/examples/simpleclient/src/main/assets/oic_svr_db_client.json @@ -8,38 +8,32 @@ {
"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": ""
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
},
{
"href": "/oic/ad",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.ad"],
+ "if": ["oic.if.baseline"]
},
{
- "href": "/oic/sec/acl",
+ "href": "/oic/sec/amacl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.amacl"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 2
@@ -50,14 +44,14 @@ {
"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": 2
@@ -83,7 +77,7 @@ "deviceuuid": "32323232-3232-3232-3232-323232323232",
"devowneruuid": "32323232-3232-3232-3232-323232323232",
"rowneruuid": "32323232-3232-3232-3232-323232323232",
- "dpc": false
+ "x.org.iotivity.dpc": false
},
"cred": {
"creds": [
diff --git a/android/examples/simpleserver/src/main/assets/oic_svr_db_server.dat b/android/examples/simpleserver/src/main/assets/oic_svr_db_server.dat Binary files differindex 31e18140a..706a03078 100644 --- a/android/examples/simpleserver/src/main/assets/oic_svr_db_server.dat +++ b/android/examples/simpleserver/src/main/assets/oic_svr_db_server.dat diff --git a/android/examples/simpleserver/src/main/assets/oic_svr_db_server.json b/android/examples/simpleserver/src/main/assets/oic_svr_db_server.json index 0e1bf23a1..d36503adf 100644 --- a/android/examples/simpleserver/src/main/assets/oic_svr_db_server.json +++ b/android/examples/simpleserver/src/main/assets/oic_svr_db_server.json @@ -8,38 +8,32 @@ {
"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": ""
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
},
{
"href": "/oic/ad",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.ad"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/acl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.acl"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 2
@@ -50,14 +44,14 @@ {
"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": 2
@@ -68,20 +62,20 @@ {
"href": "/a/light",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/a/light0",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/a/light1",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 6
@@ -107,7 +101,7 @@ "deviceuuid": "31313131-3131-3131-3131-313131313131",
"devowneruuid": "32323232-3232-3232-3232-323232323232",
"rowneruuid": "31313131-3131-3131-3131-313131313131",
- "dpc": false
+ "x.org.iotivity.dpc": false
},
"cred": {
"creds": [
diff --git a/build_common/SConscript b/build_common/SConscript index b6309ca4b..35acb31a6 100644 --- a/build_common/SConscript +++ b/build_common/SConscript @@ -14,8 +14,8 @@ host_target_map = { # 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'], @@ -180,6 +180,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) @@ -295,11 +303,6 @@ if env.get('ROUTING') == 'GW': elif env.get('ROUTING') == 'EP': routing_define = 'ROUTING_EP' -if env.get('SECURED') == '1': - ocpmapi_lib = '-locpmapi' -elif env.get('SECURED') == '0': - ocpmapi_lib = '' - user_prefix = env.get('PREFIX') user_lib = env.get('LIB_INSTALL_DIR') if not user_lib: @@ -308,18 +311,16 @@ 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, - '\@OCPMAPI_LIB\@': ocpmapi_lib + '\@ROUTING_DEFINE\@': routing_define } else: pc_vars = {'\@PREFIX\@': env.get('BUILD_DIR'), '\@EXEC_PREFIX\@': env.get('BUILD_DIR'), - '\@VERSION\@': '1.0.1', + '\@VERSION\@': '1.1.1', '\@LIB_INSTALL_DIR\@': user_lib, - '\@ROUTING_DEFINE\@': routing_define, - '\@OCPMAPI_LIB\@': ocpmapi_lib + '\@ROUTING_DEFINE\@': routing_define } env.Substfile(pc_file, SUBST_DICT = pc_vars) @@ -382,8 +383,7 @@ if target_os == "yocto": env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__', '_GNU_SOURCE']) env.AppendUnique(CFLAGS = ['-std=gnu99']) env.AppendUnique(CCFLAGS = ['-Wall', '-Wextra', '-fPIC']) - env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread']) - env.AppendUnique(LIBS = ['uuid']) + env.AppendUnique(LIBS = ['dl', 'pthread', 'uuid']) Export('env') else: ''' diff --git a/build_common/android/SConscript b/build_common/android/SConscript index ef6715f3a..97c617f9a 100644 --- a/build_common/android/SConscript +++ b/build_common/android/SConscript @@ -215,7 +215,6 @@ if env.get('LOGGING'): env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__ANDROID__']) env.AppendUnique(CCFLAGS = ['-Wall', '-Wextra', '-fPIC']) -#env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread']) env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) env.AppendUnique(LIBPATH = [src_dir + '/resource/csdk/connectivity/lib/android']) diff --git a/build_common/linux/SConscript b/build_common/linux/SConscript index 6a9393b79..231152035 100644 --- a/build_common/linux/SConscript +++ b/build_common/linux/SConscript @@ -19,8 +19,8 @@ if env.get('LOGGING'): env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__']) env.AppendUnique(CFLAGS = ['-std=gnu99']) env.AppendUnique(CCFLAGS = ['-Wall', '-Wextra', '-fPIC']) +env.AppendUnique(LIBS = ['dl', 'pthread']) env.AppendUnique(LIBS = ['uuid']) -env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread']) # Set arch flags that match best TARGET_ARCH variable target_arch = env.get('TARGET_ARCH') diff --git a/build_common/tizen/SConscript b/build_common/tizen/SConscript index 15472b458..3f629a60c 100644 --- a/build_common/tizen/SConscript +++ b/build_common/tizen/SConscript @@ -20,7 +20,7 @@ env['CCFLAGS'] = SCons.Util.CLVar(os.environ.get('CFLAGS', "")) env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__']) env.AppendUnique(CFLAGS = ['-std=gnu99']) env.AppendUnique(CCFLAGS = ['-Wextra', '-fPIC']) -env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread']) +env.AppendUnique(LIBS = ['dl', 'pthread']) env.AppendUnique(CCFLAGS = ['-D__TIZEN__', '-D_GNU_SOURCE', '-DTIZEN_DEBUG_ENABLE']) env.ParseConfig("pkg-config dlog --cflags --libs") diff --git a/examples/OICMiddle/SConscript b/examples/OICMiddle/SConscript index 8c1152d4e..0840ef36f 100644 --- a/examples/OICMiddle/SConscript +++ b/examples/OICMiddle/SConscript @@ -24,7 +24,7 @@ Import('env') # Add third party libraries lib_env = env.Clone() -SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env') +SConscript('#resource/third_party_libs.scons', 'lib_env') examples_env = lib_env.Clone() @@ -46,11 +46,16 @@ if target_os not in ['windows', 'winrt']: # 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': - examples_env.AppendUnique(LIBS = ['-lpthread']) + examples_env.AppendUnique(LIBS = ['pthread']) examples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) -examples_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', - 'coap', 'rt']) +examples_env.PrependUnique(LIBS = ['coap']) +examples_env.AppendUnique(LIBS = ['connectivity_abstraction']) +examples_env.AppendUnique(LIBS = ['oc_logger']) +examples_env.AppendUnique(LIBS = ['octbstack']) +examples_env.AppendUnique(LIBS = ['oc']) +examples_env.AppendUnique(LIBS = ['rt']) + if env.get('SECURED') == '1': examples_env.AppendUnique(LIBS = ['tinydtls']) diff --git a/extlibs/gtest/SConscript b/extlibs/gtest/SConscript index 6ecdcd166..4bcabc113 100644 --- a/extlibs/gtest/SConscript +++ b/extlibs/gtest/SConscript @@ -1,6 +1,6 @@ ## -# 'googletest' script to check if Google Unit Test library is installed. If not, -# get it and install it +# 'googletest' script to check if Google Unit Test library is installed. +# If not, get it and install it # ## @@ -8,46 +8,43 @@ import os Import('env') -target_os = env.get('TARGET_OS') -src_dir = env.get('SRC_DIR') +gtest_env = env.Clone() +target_os = gtest_env.get('TARGET_OS') +src_dir = gtest_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' +gtest_dir = os.path.join(src_dir, 'extlibs', 'gtest', 'gtest-1.7.0') +gtest_lib_dir = os.path.join(gtest_dir,'lib') +gtest_dotlib_dir = os.path.join(gtest_lib_dir, '.libs') +gtest_zip_file = os.path.join(src_dir, 'extlibs', 'gtest', 'gtest-1.7.0.zip') gtest_url = 'https://googletest.googlecode.com/files/gtest-1.7.0.zip' 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 not os.path.exists(os.path.join(gtest_dir, 'configure')): # If the gtest zip file is not already present, download it if not os.path.exists(gtest_zip_file): - gtest_zip = env.Download(gtest_zip_file, gtest_url) + gtest_zip = gtest_env.Download(gtest_zip_file, gtest_url) else: gtest_zip = gtest_zip_file - - # Unzip gtest - print 'Unzipping google unit test' - env.UnpackAll(gtest_dir, gtest_zip) - + print 'Unzipping to : ' + gtest_dir + gtest_env.UnpackAll(gtest_dir, gtest_zip) if target_os == 'darwin': if os.path.exists(gtest_dir): # Build gtest and store it at a temporary directory - gtest_lib_dir = gtest_dir + '/lib' - gtest_dotlib_dir = gtest_lib_dir + '/.libs' - if not os.path.exists(gtest_lib_dir): + if not os.path.exists(gtest_lib_dir): # print 'Create a directory' # os.mkdir(gtest_lib_dir) print 'Invoke cmake command to generate appropriate make files' - env.Configure(gtest_dir, './configure') + gtest_env.Configure(gtest_dir, './configure') # Run make on gtest print 'Making google unit test' - env.Configure(gtest_dir, 'make') + gtest_env.Configure(gtest_dir, 'make') # print 'Create a directory' # os.mkdir(gtest_dotlib_dir) @@ -64,18 +61,33 @@ if target_os == 'darwin': print 'Create hard links pointing to gtest libraries - DONE' -elif target_os == 'linux': +elif target_os in ['linux']: if os.path.exists(gtest_dir): - if not os.path.exists(gtest_dir + "/lib"): + if not os.path.exists(gtest_lib_dir): # 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') + gtest_env.Configure(gtest_dir, 'make') +# Export flags once for all +if target_os in targets_need_gtest: + gtest_env.AppendUnique(LIBPATH = [gtest_dotlib_dir]) + gtest_env.PrependUnique(CPPPATH = [os.path.join(gtest_dir, 'include')]) + gtest_env.AppendENVPath('LD_LIBRARY_PATH', gtest_dotlib_dir) + if 'g++' in gtest_env.get('CXX'): + gtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x']) + gtest_env.AppendUnique(CXXFLAGS = ['-Wall']) +# Note: 'pthread' for android is in bionic +# On other platform, if use new gcc(>4.9?) it isn't required, otherwise, it's required + if target_os not in ['android']: + gtest_env.AppendUnique(CXXFLAGS = ['-pthread']) + gtest_env.PrependUnique(LIBS = ['pthread']) + gtest_env.PrependUnique(LIBS = ['gtest', 'gtest_main']) + +Return('gtest_env') diff --git a/extlibs/tinycbor/SConscript b/extlibs/tinycbor/SConscript index 8c6a49765..e5f20576b 100644 --- a/extlibs/tinycbor/SConscript +++ b/extlibs/tinycbor/SConscript @@ -30,7 +30,8 @@ if not os.path.exists(cborDir): print ''' *********************************** Error: **************************************** * Please download cbor using the following command: * -* $ git clone https://github.com/01org/tinycbor.git extlibs/tinycbor/tinycbor * +* $ git clone https://github.com/01org/tinycbor.git extlibs/tinycbor/tinycbor \ * +* -b v0.2.1 * *********************************************************************************** ''' Exit(1) diff --git a/extlibs/tinydtls/dtls.c b/extlibs/tinydtls/dtls.c index 6cf26b4a3..bb26ade39 100644 --- a/extlibs/tinydtls/dtls.c +++ b/extlibs/tinydtls/dtls.c @@ -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; @@ -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: @@ -4748,7 +4785,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 +4830,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 +4873,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 diff --git a/extlibs/tinydtls/hmac.h b/extlibs/tinydtls/hmac.h index afdfaea8b..0eacd9993 100644 --- a/extlibs/tinydtls/hmac.h +++ b/extlibs/tinydtls/hmac.h @@ -35,23 +35,23 @@ * 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 dtls_hash_init(dtls_hash_t ctx) { - DTLS_SHA256_Init((DTLS_SHA256_CTX *)ctx); + dtls_sha256_init((dtls_sha256_ctx *)ctx); } static inline 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 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 */ diff --git a/extlibs/tinydtls/sha2/sha2.c b/extlibs/tinydtls/sha2/sha2.c index 4d729e7ab..c42c9932c 100644 --- a/extlibs/tinydtls/sha2/sha2.c +++ b/extlibs/tinydtls/sha2/sha2.c @@ -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 diff --git a/extlibs/tinydtls/sha2/sha2.h b/extlibs/tinydtls/sha2/sha2.h index e6eecc4b8..c56b42aa2 100644 --- a/extlibs/tinydtls/sha2/sha2.h +++ b/extlibs/tinydtls/sha2/sha2.h @@ -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 */ diff --git a/extlibs/tinydtls/sha2/sha2prog.c b/extlibs/tinydtls/sha2/sha2prog.c index b5c485e67..6ac679685 100644 --- a/extlibs/tinydtls/sha2/sha2prog.c +++ b/extlibs/tinydtls/sha2/sha2prog.c @@ -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); diff --git a/extlibs/tinydtls/sha2/sha2speed.c b/extlibs/tinydtls/sha2/sha2speed.c index f012f4049..77d17aff9 100644 --- a/extlibs/tinydtls/sha2/sha2speed.c +++ b/extlibs/tinydtls/sha2/sha2speed.c @@ -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; diff --git a/extlibs/tinydtls/tests/pcap.c b/extlibs/tinydtls/tests/pcap.c index 8f72f26be..b53dc8cdf 100644 --- a/extlibs/tinydtls/tests/pcap.c +++ b/extlibs/tinydtls/tests/pcap.c @@ -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]) diff --git a/gbsbuild.sh b/gbsbuild.sh index 9ba4a7287..84fe3acf7 100755 --- a/gbsbuild.sh +++ b/gbsbuild.sh @@ -30,8 +30,9 @@ 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 -LR ./extlibs/sqlite3 $sourcedir/tmp/extlibs cp -R ./extlibs/timer $sourcedir/tmp/extlibs cp -R ./extlibs/rapidxml $sourcedir/tmp/extlibs cp -R ./resource $sourcedir/tmp diff --git a/iotivity.pc.in b/iotivity.pc.in index 382cbc661..e98ed1b51 100644 --- a/iotivity.pc.in +++ b/iotivity.pc.in @@ -11,8 +11,7 @@ Description: IoTivity is an open source reference implementation of the OIC stan Version: @VERSION@ URL: https://www.iotivity.org Requires: -Libs: -L${libdir} -loc -loc_logger -loc_logger_core -loctbstack -lconnectivity_abstraction \ - @OCPMAPI_LIB@ +Libs: -L${libdir} -loc -loc_logger -loc_logger_core -loctbstack -lconnectivity_abstraction -locpmapi Cflags: -I${includedir}/resource \ -I${svcincludedir}/resource-encapsulation \ -I${svcincludedir}/resource-container \ diff --git a/packaging/iotivity.spec b/packaging/iotivity.spec index 67fd1e27c..566761f52 100644 --- a/packaging/iotivity.spec +++ b/packaging/iotivity.spec @@ -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 @@ -36,6 +36,7 @@ Requires(post): /sbin/ldconfig %{!?ES_TARGET_ENROLLEE: %define ES_TARGET_ENROLLEE tizen} %{!?ES_ROLE: %define ES_ROLE enrollee} %{!?ES_SOFTAP_MODE: %define ES_SOFTAP_MODE MEDIATOR_SOFTAP} +%{!?VERBOSE: %define VERBOSE 0} %description An open source reference implementation of the OIC standard specifications @@ -101,8 +102,8 @@ cp %{SOURCE1001} ./%{name}-test.manifest %define RPM_ARCH "x86" %endif -#VERBOSE=1 scons -j2 --prefix=%{_prefix} \ + VERBOSE=%{VERBOSE} \ TARGET_OS=tizen TARGET_ARCH=%{RPM_ARCH} TARGET_TRANSPORT=%{TARGET_TRANSPORT} \ RELEASE=%{RELEASE} SECURED=1 LOGGING=%{LOGGING} ROUTING=%{ROUTING} \ ES_TARGET_ENROLLEE=%{ES_TARGET_ENROLLEE} ES_ROLE=%{ES_ROLE} ES_SOFTAP_MODE=%{ES_SOFTAP_MODE} \ @@ -152,6 +153,10 @@ cp out/tizen/*/%{build_mode}/resource/examples/oic_svr_db_client.dat %{ex_instal mkdir -p %{ex_install_dir}/provisioning cp out/tizen/*/%{build_mode}/resource/csdk/security/provisioning/sample/provisioningclient %{ex_install_dir}/provisioning/ cp out/tizen/*/%{build_mode}/resource/csdk/security/provisioning/sample/oic_svr_db_client.dat %{ex_install_dir}/provisioning/ +cp out/tizen/*/%{build_mode}/resource/csdk/security/provisioning/sample/sampleserver_justworks %{ex_install_dir}/provisioning/ +cp out/tizen/*/%{build_mode}/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat %{ex_install_dir}/provisioning/ +cp out/tizen/*/%{build_mode}/resource/csdk/security/provisioning/sample/sampleserver_randompin %{ex_install_dir}/provisioning/ +cp out/tizen/*/%{build_mode}/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat %{ex_install_dir}/provisioning/ cp ./resource/csdk/security/include/pinoxmcommon.h %{buildroot}%{_includedir} cp ./resource/csdk/security/include/securevirtualresourcetypes.h %{buildroot}%{_includedir} @@ -168,6 +173,7 @@ cp LICENSE.APLv2 %{buildroot}/%{_datadir}/license/%{name}-service cp LICENSE.APLv2 %{buildroot}/%{_datadir}/license/%{name}-test %endif +cp service/things-manager/sdk/inc/*.h %{buildroot}%{_includedir} cp service/easy-setup/inc/*.h %{buildroot}%{_includedir} cp service/easy-setup/enrollee/inc/*.h %{buildroot}%{_includedir} diff --git a/plugins/samples/linux/IotivityandZigbeeServer.c b/plugins/samples/linux/IotivityandZigbeeServer.c index dc011aa8b..da7b4ac00 100644 --- a/plugins/samples/linux/IotivityandZigbeeServer.c +++ b/plugins/samples/linux/IotivityandZigbeeServer.c @@ -139,7 +139,11 @@ 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; diff --git a/plugins/unittests/SConscript b/plugins/unittests/SConscript index bd225dd81..bd399d7d7 100644 --- a/plugins/unittests/SConscript +++ b/plugins/unittests/SConscript @@ -18,26 +18,28 @@ # #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -Import('env') import os import os.path -unittests_env = env.Clone() +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +unittests_env = gtest_env.Clone() src_dir = unittests_env.get('SRC_DIR') pi_dir = os.path.join(src_dir, 'plugins') -build_dir = env.get('BUILD_DIR') +build_dir = unittests_env.get('BUILD_DIR') +target_os = unittests_env.get('TARGET_OS') + ###################################################################### # Build flags ###################################################################### unittests_env.PrependUnique(CPPPATH = [ os.path.join(pi_dir, 'include'), - '#extlibs/gtest/gtest-1.7.0/include', ]) -unittests_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) -unittests_env.PrependUnique(LIBS = ['-lpthread']) -unittests_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) -unittests_env.AppendUnique(LIBPATH = [os.path.join(src_dir, 'extlibs', 'gtest', 'gtest-1.7.0', 'lib', '.libs')]) +if target_os not in ['windows']: + unittests_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) + unittests_env.PrependUnique(LIBS = ['pthread']) +unittests_env.AppendUnique(LIBPATH = [unittests_env.get('BUILD_DIR')]) unittests_env.PrependUnique(LIBS = [ 'plugin_interface', 'oc', @@ -49,7 +51,7 @@ unittests_env.PrependUnique(LIBS = [ 'gtest_main' ]) -if env.get('LOGGING'): +if unittests_env.get('LOGGING'): unittests_env.AppendUnique(CPPDEFINES = ['TB_LOG']) ###################################################################### @@ -59,10 +61,9 @@ piunittests = unittests_env.Program('piunittests', ['plugininterfacetest.cpp']) Alias("piunittests", [piunittests]) -env.AppendTarget('piunittests') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': +unittests_env.AppendTarget('piunittests') +if unittests_env.get('TEST') == '1': + if target_os in ['linux']: from tools.scons.RunTest import * run_test(unittests_env, 'plugins_unittests.memcheck', diff --git a/resource/SConscript b/resource/SConscript index 363771755..b07bc9576 100644 --- a/resource/SConscript +++ b/resource/SConscript @@ -30,9 +30,8 @@ Import('env') target_os = env.get('TARGET_OS') src_dir = env.get('SRC_DIR') -if target_os not in ['tizen']: - # Build liblogger - SConscript('csdk/logger/SConscript') +# Build liblogger +SConscript('csdk/logger/SConscript') if target_os not in ['arduino', 'darwin', 'ios', 'android']: env.AppendUnique(LIBS=['rt']) diff --git a/resource/c_common/ocrandom/test/SConscript b/resource/c_common/ocrandom/test/SConscript index 86e08a1fb..c813d2f1e 100644 --- a/resource/c_common/ocrandom/test/SConscript +++ b/resource/c_common/ocrandom/test/SConscript @@ -18,12 +18,13 @@ # #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -Import('env') import os import os.path -randomtest_env = env.Clone() -src_dir = randomtest_env.get('SRC_DIR') +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +randomtest_env = gtest_env.Clone() +target_os = randomtest_env.get('TARGET_OS') ###################################################################### # Build flags @@ -32,21 +33,22 @@ randomtest_env.PrependUnique(CPPPATH = [ '../include', '../../logger/include', '../../../oc_logger/include', - '../../../../extlibs/gtest/gtest-1.7.0/include' ]) -randomtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) -randomtest_env.AppendUnique(LIBS = ['-lpthread']) -randomtest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) -randomtest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs']) -randomtest_env.PrependUnique(LIBS = ['m', - 'octbstack', +if target_os not in ['windows']: + randomtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) + randomtest_env.AppendUnique(LIBS = ['pthread']) + +randomtest_env.AppendUnique(LIBPATH = [randomtest_env.get('BUILD_DIR')]) +randomtest_env.PrependUnique(LIBS = ['octbstack', 'uuid', 'gtest', 'gtest_main']) +if target_os in ['linux']: + randomtest_env.AppendUnique(LIBS = ['m']) -if env.get('LOGGING'): +if randomtest_env.get('LOGGING'): randomtest_env.AppendUnique(CPPDEFINES = ['TB_LOG']) ###################################################################### @@ -56,10 +58,9 @@ randomtests = randomtest_env.Program('randomtests', ['linux/randomtest.cpp']) Alias("test", [randomtests]) -env.AppendTarget('test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': +randomtest_env.AppendTarget('test') +if randomtest_env.get('TEST') == '1': + if target_os in ['linux']: from tools.scons.RunTest import * run_test(randomtest_env, 'resource_csdk_random_test.memcheck', diff --git a/resource/c_common/oic_malloc/test/SConscript b/resource/c_common/oic_malloc/test/SConscript index 0b702ec5e..89c670512 100644 --- a/resource/c_common/oic_malloc/test/SConscript +++ b/resource/c_common/oic_malloc/test/SConscript @@ -18,24 +18,27 @@ # #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -Import('env') import os +import os.path -malloctest_env = env.Clone() -src_dir = malloctest_env.get('SRC_DIR') +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +malloctest_env = gtest_env.Clone() +target_os = malloctest_env.get('TARGET_OS') ###################################################################### # Build flags ###################################################################### malloctest_env.PrependUnique(CPPPATH = [ - '../include', - '#extlibs/gtest/gtest-1.7.0/include' ]) + '../include']) -malloctest_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/c_common')]) -malloctest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs']) -malloctest_env.PrependUnique(LIBS = ['c_common', 'gtest', 'gtest_main', 'pthread']) +if target_os not in ['windows']: + malloctest_env.PrependUnique(LIBS = ['pthread']) -if env.get('LOGGING'): +malloctest_env.AppendUnique(LIBPATH = [os.path.join(malloctest_env.get('BUILD_DIR'), 'resource', 'c_common')]) +malloctest_env.PrependUnique(LIBS = ['c_common', 'gtest', 'gtest_main']) + +if malloctest_env.get('LOGGING'): malloctest_env.AppendUnique(CPPDEFINES = ['TB_LOG']) # ###################################################################### @@ -45,10 +48,9 @@ malloctests = malloctest_env.Program('malloctests', ['linux/oic_malloc_tests.cpp Alias("test", [malloctests]) -env.AppendTarget('test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': +malloctest_env.AppendTarget('test') +if malloctest_env.get('TEST') == '1': + if target_os in ['linux']: from tools.scons.RunTest import * run_test(malloctest_env, 'resource_ccommon_malloc_test.memcheck', diff --git a/resource/c_common/oic_string/test/SConscript b/resource/c_common/oic_string/test/SConscript index 9d3025163..77cc2a001 100644 --- a/resource/c_common/oic_string/test/SConscript +++ b/resource/c_common/oic_string/test/SConscript @@ -18,24 +18,24 @@ # #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -Import('env') import os +import os.path -stringtest_env = env.Clone() -src_dir = stringtest_env.get('SRC_DIR') +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +stringtest_env = gtest_env.Clone() +target_os = stringtest_env.get('TARGET_OS') ###################################################################### # Build flags ###################################################################### stringtest_env.PrependUnique(CPPPATH = [ - '../include', - '#extlibs/gtest/gtest-1.7.0/include' ]) + '../include']) -stringtest_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/c_common')]) -stringtest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs']) +stringtest_env.AppendUnique(LIBPATH = [os.path.join(stringtest_env.get('BUILD_DIR'), 'resource', 'c_common')]) stringtest_env.PrependUnique(LIBS = ['c_common', 'gtest', 'gtest_main', 'pthread']) -if env.get('LOGGING'): +if stringtest_env.get('LOGGING'): stringtest_env.AppendUnique(CPPDEFINES = ['TB_LOG']) # ###################################################################### @@ -45,9 +45,8 @@ stringtests = stringtest_env.Program('stringtests', ['linux/oic_string_tests.cpp Alias("test", [stringtests]) -env.AppendTarget('test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') +stringtest_env.AppendTarget('test') +if stringtest_env.get('TEST') == '1': if target_os == 'linux': from tools.scons.RunTest import * run_test(stringtest_env, diff --git a/resource/c_common/oic_time/test/SConscript b/resource/c_common/oic_time/test/SConscript index 222b9e856..64d402169 100644 --- a/resource/c_common/oic_time/test/SConscript +++ b/resource/c_common/oic_time/test/SConscript @@ -18,27 +18,28 @@ # #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -Import('env') import os +import os.path - -timetest_env = env.Clone() -src_dir = timetest_env.get('SRC_DIR') +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +timetest_env = gtest_env.Clone() +target_os = timetest_env.get('TARGET_OS') ###################################################################### # Build flags ###################################################################### timetest_env.PrependUnique(CPPPATH = [ - '../include', - '#extlibs/gtest/gtest-1.7.0/include' ]) + '../include']) -timetest_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/c_common')]) -timetest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs']) -timetest_env.PrependUnique(LIBS = ['c_common', 'gtest', 'gtest_main', 'pthread']) +timetest_env.AppendUnique(LIBPATH = [os.path.join(timetest_env.get('BUILD_DIR'), 'resource', 'c_common')]) +if target_os not in ['windows']: + timetest_env.PrependUnique(LIBS = ['pthread']) +timetest_env.PrependUnique(LIBS = ['gtest', 'gtest_main']) +timetest_env.PrependUnique(LIBS = ['c_common']) timetest_env.Append(LIBS = ['rt']); -if env.get('LOGGING'): +if timetest_env.get('LOGGING'): timetest_env.AppendUnique(CPPDEFINES = ['TB_LOG']) # ###################################################################### @@ -48,10 +49,9 @@ timetests = timetest_env.Program('timetests', ['linux/oic_time_tests.cpp']) Alias("test", [timetests]) -env.AppendTarget('test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': +timetest_env.AppendTarget('test') +if timetest_env.get('TEST') == '1': + if target_os in ['linux']: from tools.scons.RunTest import * run_test(timetest_env, 'resource_ccommon_time_test.memcheck', diff --git a/resource/csdk/connectivity/api/cacommon.h b/resource/csdk/connectivity/api/cacommon.h index 1983fa21a..be30106c0 100644 --- a/resource/csdk/connectivity/api/cacommon.h +++ b/resource/csdk/connectivity/api/cacommon.h @@ -514,6 +514,8 @@ typedef struct struct tcpsockets { void *threadpool; /**< threadpool between Initialize and Start */ + CASocket_t ipv4; /**< IPv4 accept socket */ + CASocket_t ipv6; /**< IPv6 accept socket */ void *svrlist; /**< unicast IPv4 TCP server information*/ int selectTimeout; /**< in seconds */ int listenBacklog; /**< backlog counts*/ @@ -523,6 +525,7 @@ typedef struct bool started; /**< the TCP adapter has started */ bool terminate; /**< the TCP adapter needs to stop */ bool ipv4tcpenabled; /**< IPv4 TCP enabled by OCInit flags */ + bool ipv6tcpenabled; /**< IPv6 TCP enabled by OCInit flags */ } tcp; #endif } CAGlobals_t; diff --git a/resource/csdk/connectivity/api/cainterface.h b/resource/csdk/connectivity/api/cainterface.h index a2538462f..5d50d8dd0 100644 --- a/resource/csdk/connectivity/api/cainterface.h +++ b/resource/csdk/connectivity/api/cainterface.h @@ -69,22 +69,14 @@ typedef struct * Callback function to pass the connection information from CA to RI. * @param[out] object remote device information. */ -typedef void (*CAKeepAliveConnectedCallback)(const CAEndpoint_t *object); +typedef void (*CAKeepAliveConnectionCallback)(const CAEndpoint_t *object, bool isConnected); /** - * Callback function to pass the disconnection information from CA to RI. - * @param[out] object remote device information. - */ -typedef void (*CAKeepAliveDisconnectedCallback)(const CAEndpoint_t *object); - -/** - * Register connected callback and disconnected callback to process KeepAlive. + * Register connection status changes callback to process KeepAlive. * connection informations are delivered these callbacks. - * @param[in] ConnHandler Connected callback. - * @param[in] DisconnHandler Disconnected Callback. + * @param[in] ConnHandler Connection status changes callback. */ -void CARegisterKeepAliveHandler(CAKeepAliveConnectedCallback ConnHandler, - CAKeepAliveDisconnectedCallback DisconnHandler); +void CARegisterKeepAliveHandler(CAKeepAliveConnectionCallback ConnHandler); #endif /** * Initialize the connectivity abstraction module. diff --git a/resource/csdk/connectivity/api/casecurityinterface.h b/resource/csdk/connectivity/api/casecurityinterface.h index 3d1287048..cab30a770 100644 --- a/resource/csdk/connectivity/api/casecurityinterface.h +++ b/resource/csdk/connectivity/api/casecurityinterface.h @@ -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. diff --git a/resource/csdk/connectivity/build/SConscript b/resource/csdk/connectivity/build/SConscript index e829d4b5a..1c1e9cc44 100644 --- a/resource/csdk/connectivity/build/SConscript +++ b/resource/csdk/connectivity/build/SConscript @@ -174,8 +174,11 @@ def __install(ienv, targets, name): def __installlib(ienv, targets, name): user_prefix = env.get('PREFIX') if user_prefix: - i_n = ienv.Install(user_prefix + '/lib', targets) - ienv.Alias("install", i_n) + install_lib_dir = os.path.join(user_prefix, 'lib') + else: + install_lib_dir = os.path.join(env.get('BUILD_DIR'), 'lib') + i_n = ienv.Install(install_lib_dir, targets) + ienv.Alias("install", i_n) def __installbin(ienv, targets, name): user_prefix = env.get('PREFIX') @@ -269,7 +272,8 @@ if target_os == "yocto": env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__', '_GNU_SOURCE']) env.AppendUnique(CFLAGS = ['-std=gnu99']) env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC']) - env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread']) + if target_os in ['linux']: + env.AppendUnique(LIBS = ['dl', 'pthread']) Export('env') else: ''' diff --git a/resource/csdk/connectivity/build/android/SConscript b/resource/csdk/connectivity/build/android/SConscript index 1a5078505..b2f929721 100644 --- a/resource/csdk/connectivity/build/android/SConscript +++ b/resource/csdk/connectivity/build/android/SConscript @@ -168,7 +168,6 @@ if env.get('LOGGING'): env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__ANDROID__']) env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC']) -#env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread']) env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) src_dir = env.get('SRC_DIR') diff --git a/resource/csdk/connectivity/build/linux/SConscript b/resource/csdk/connectivity/build/linux/SConscript index bc0176d1c..d44b5af0f 100644 --- a/resource/csdk/connectivity/build/linux/SConscript +++ b/resource/csdk/connectivity/build/linux/SConscript @@ -18,7 +18,7 @@ if env.get('LOGGING'): env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__']) env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC']) -env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread']) +env.AppendUnique(LIBS = ['dl', 'pthread']) # Set arch flags target_arch = env.get('TARGET_ARCH') diff --git a/resource/csdk/connectivity/build/tizen/gbsbuild.sh b/resource/csdk/connectivity/build/tizen/gbsbuild.sh index 14c6f9038..d7c12a66a 100755 --- a/resource/csdk/connectivity/build/tizen/gbsbuild.sh +++ b/resource/csdk/connectivity/build/tizen/gbsbuild.sh @@ -58,6 +58,8 @@ cp -R ./extlibs/timer/ $sourcedir/tmp/con/extlibs/ mkdir -p $sourcedir/tmp/con/c_common cp -R ./resource/c_common/* $sourcedir/tmp/con/c_common/ cp -R ./resource/csdk/logger/include/* $sourcedir/tmp/con/common/inc/ +mkdir ./tmp/con/logger/ +cp -R ./resource/csdk/logger/* $sourcedir/tmp/con/logger # copy dependency RPMs and conf files for tizen build cp ./tools/tizen/*.rpm $sourcedir/tmp diff --git a/resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec b/resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec index 1346ff9e0..70b52d14d 100644 --- a/resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec +++ b/resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec @@ -2,10 +2,12 @@ %define ROOTDIR %{_builddir}/%{name}-%{version} %define DEST_INC_DIR %{buildroot}/%{_includedir}/OICHeaders %define DEST_LIB_DIR %{buildroot}/%{_libdir} +%{!?VERBOSE: %define VERBOSE 1} + 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 @@ -35,7 +37,7 @@ SLP oicca application echo %{ROOTDIR} scons TARGET_OS=tizen -c -scons TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} LOGGING=%{LOGGING} WITH_TCP=%{WITH_TCP} +scons VERBOSE=%{VERBOSE} TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} LOGGING=%{LOGGING} WITH_TCP=%{WITH_TCP} %install mkdir -p %{DEST_INC_DIR} diff --git a/resource/csdk/connectivity/build/tizen/scons/SConscript b/resource/csdk/connectivity/build/tizen/scons/SConscript index a06d5eee5..aee4ce380 100644 --- a/resource/csdk/connectivity/build/tizen/scons/SConscript +++ b/resource/csdk/connectivity/build/tizen/scons/SConscript @@ -52,3 +52,4 @@ else: env.SConscript(['../con/lib/libcoap-4.1.1/SConscript']) env.SConscript(['../con/SConscript']) env.SConscript(['../con/c_common/SConscript']) +env.SConscript(['../con/logger/SConscript'])
\ No newline at end of file diff --git a/resource/csdk/connectivity/inc/caadapterinterface.h b/resource/csdk/connectivity/inc/caadapterinterface.h index 8e029add5..144f3838a 100644 --- a/resource/csdk/connectivity/inc/caadapterinterface.h +++ b/resource/csdk/connectivity/inc/caadapterinterface.h @@ -188,9 +188,13 @@ typedef void (*CANetworkPacketReceivedCallback)(const CASecureEndpoint_t *sep, /** * This will be used to notify network changes to the connectivity common logic layer. - * @see SendUnicastData(), SendMulticastData() */ -typedef void (*CANetworkChangeCallback)(const CAEndpoint_t *info, CANetworkStatus_t status); +typedef void (*CAAdapterChangeCallback)(CATransportAdapter_t adapter, CANetworkStatus_t status); + +/** + * This will be used to notify connection changes to the connectivity common logic layer. + */ +typedef void (*CAConnectionChangeCallback)(const CAEndpoint_t *info, bool isConnected); /** * This will be used to notify error result to the connectivity common logic layer. diff --git a/resource/csdk/connectivity/inc/caedradapter.h b/resource/csdk/connectivity/inc/caedradapter.h index 88794e303..bec17b706 100644 --- a/resource/csdk/connectivity/inc/caedradapter.h +++ b/resource/csdk/connectivity/inc/caedradapter.h @@ -44,7 +44,9 @@ extern "C" * Abstraction Layer. * @param[in] reqRespCallback Callback to notify request and response messages from * server(s) started at Connectivity Abstraction Layer. - * @param[in] netCallback Callback to notify the network additions to Connectivity + * @param[in] netCallback Callback to notify the adapter changes to Connectivity + * Abstraction Layer. + * @param[in] connCallback Callback to notify the connection changes to Connectivity * Abstraction Layer. * @param[in] errorCallback errorCallback to notify error to connectivity common logic * layer from adapter. @@ -52,8 +54,9 @@ extern "C" * @return ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h). */ CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback, - CANetworkPacketReceivedCallback reqRespCallback, - CANetworkChangeCallback netCallback, + CANetworkPacketReceivedCallback packetReceivedCallback, + CAAdapterChangeCallback netCallback, + CAConnectionChangeCallback connCallback, CAErrorHandleCallback errorCallback, ca_thread_pool_t handle); /** diff --git a/resource/csdk/connectivity/inc/caedradapter_singlethread.h b/resource/csdk/connectivity/inc/caedradapter_singlethread.h index f2422ae40..f1cba2664 100644 --- a/resource/csdk/connectivity/inc/caedradapter_singlethread.h +++ b/resource/csdk/connectivity/inc/caedradapter_singlethread.h @@ -55,7 +55,7 @@ extern "C" */ CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback, CANetworkPacketReceivedCallback reqRespCallback, - CANetworkChangeCallback netCallback); + CAAdapterChangeCallback netCallback); /** * @brief Starting EDR connectivity adapters. As its peer to peer it doesnot require to start diff --git a/resource/csdk/connectivity/inc/cainterfacecontroller.h b/resource/csdk/connectivity/inc/cainterfacecontroller.h index 477674fe9..edf060f24 100644 --- a/resource/csdk/connectivity/inc/cainterfacecontroller.h +++ b/resource/csdk/connectivity/inc/cainterfacecontroller.h @@ -67,11 +67,12 @@ void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback); void CASetErrorHandleCallback(CAErrorHandleCallback errorCallback); /** - * Set the network status changed callback for message handler. - * @param[in] callback message handler network status callback - * to receive network changes. + * Set the network status changed callback for CAUtil. + * @param[in] adapterCB CAUtil callback to receive adapter status changes. + * @param[in] connCB CAUtil callback to receive connection status changes. */ -void CASetNetworkChangeCallback(CANetworkChangeCallback callback); +void CASetNetworkMonitorCallbacks(CAAdapterChangeCallback adapterCB, + CAConnectionChangeCallback connCB); /** * Starting different connectivity adapters based on the network selection. diff --git a/resource/csdk/connectivity/inc/cainterfacecontroller_singlethread.h b/resource/csdk/connectivity/inc/cainterfacecontroller_singlethread.h index b8234f988..6ab085ef4 100644 --- a/resource/csdk/connectivity/inc/cainterfacecontroller_singlethread.h +++ b/resource/csdk/connectivity/inc/cainterfacecontroller_singlethread.h @@ -51,12 +51,12 @@ void CAInitializeAdapters(); void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback); /** - * @brief Set the network status changed callback for message handler + * @brief Set the adapter status changed callback for message handler * @param callback [IN] message handler network status callback to receive network * changes. * @return none */ -void CASetNetworkChangeCallback(CANetworkChangeCallback callback); +void CASetNetworkChangeCallback(CAAdapterChangeCallback callback); /** * @brief Set the error handler callback for message handler diff --git a/resource/csdk/connectivity/inc/caipadapter.h b/resource/csdk/connectivity/inc/caipadapter.h index e7fa8c05c..d4ec30acc 100644 --- a/resource/csdk/connectivity/inc/caipadapter.h +++ b/resource/csdk/connectivity/inc/caipadapter.h @@ -50,7 +50,7 @@ extern "C" */ CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback, CANetworkPacketReceivedCallback networkPacketCallback, - CANetworkChangeCallback netCallback, + CAAdapterChangeCallback netCallback, CAErrorHandleCallback errorCallback, ca_thread_pool_t handle); /** diff --git a/resource/csdk/connectivity/inc/caipinterface.h b/resource/csdk/connectivity/inc/caipinterface.h index 2caf5b1da..1dc028f36 100644 --- a/resource/csdk/connectivity/inc/caipinterface.h +++ b/resource/csdk/connectivity/inc/caipinterface.h @@ -187,6 +187,30 @@ typedef struct uint32_t ipv4addr; /**< used for IPv4 only. */ } CAInterface_t; + +/** + * Callback to be notified when IP adapter connection state changes. + * + * @param[in] adapter Transport adapter. + * @param[in] status Connection status either ::CA_INTERFACE_UP or ::CA_INTERFACE_DOWN. + * @see CAIPSetConnectionStateChangeCallback() for registration. + */ +typedef void (*CAIPConnectionStateChangeCallback)(CATransportAdapter_t adapter, CANetworkStatus_t status); + +/** + * Set callback for receiving local IP adapter connection status. + * + * @param[in] adapter Callback to be notified when IP adapter connection state changes. + */ +void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback); + +/** + * Set callback for receiving local IP adapter connection status. + * + * @param[in] callback Callback to be notified when IP adapter connection state changes. + */ +void CAIPSetNetworkMonitorCallback(CAIPConnectionStateChangeCallback callback); + /** * Get a list of CAInterface_t items. * @@ -195,14 +219,14 @@ typedef struct u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex); /** - * @brief Find a new network interface. + * Find a new network interface. * * @return Description of interface (or NULL if no change) */ CAInterface_t *CAFindInterfaceChange(); /** - * @brief Let the network monitor update the polling interval. + * Let the network monitor update the polling interval. * @param [in] current polling interval * * @return desired polling interval @@ -210,7 +234,7 @@ CAInterface_t *CAFindInterfaceChange(); int CAGetPollingInterval(int interval); /** - * @brief Tell the IP server an interface has been added. + * Tell the IP server an interface has been added. */ void CAWakeUpForChange(); @@ -229,7 +253,7 @@ CAResult_t CAIPStartNetworkMonitor(); CAResult_t CAIPStopNetworkMonitor(); /** - * @brief Set callback for error handling. + * Set callback for error handling. * * @param[in] ipErrorCallback callback to notify error to the ipadapter. */ diff --git a/resource/csdk/connectivity/inc/caleadapter.h b/resource/csdk/connectivity/inc/caleadapter.h index bf85d27fa..11a0b7939 100644 --- a/resource/csdk/connectivity/inc/caleadapter.h +++ b/resource/csdk/connectivity/inc/caleadapter.h @@ -40,7 +40,9 @@ extern "C" * @param[in] reqRespCallback Callback to notify request and response * messages from server(s) started at * Connectivity Abstraction Layer. - * @param[in] netCallback Callback to notify the network additions + * @param[in] netCallback Callback to notify the adapter changes + * to Connectivity Abstraction Layer. + * @param[in] connCallback Callback to notify the connection changes * to Connectivity Abstraction Layer. * @param[in] errorCallback errorCallback to notify error to * connectivity common logic layer from adapter. @@ -50,7 +52,8 @@ extern "C" */ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback, CANetworkPacketReceivedCallback reqRespCallback, - CANetworkChangeCallback netCallback, + CAAdapterChangeCallback netCallback, + CAConnectionChangeCallback connCallback, CAErrorHandleCallback errorCallback, ca_thread_pool_t handle); diff --git a/resource/csdk/connectivity/inc/caleinterface.h b/resource/csdk/connectivity/inc/caleinterface.h index 0ac0028e8..6e78bc957 100644 --- a/resource/csdk/connectivity/inc/caleinterface.h +++ b/resource/csdk/connectivity/inc/caleinterface.h @@ -115,7 +115,7 @@ typedef CAResult_t (*CABLEDataReceivedCallback)(const char *remoteAddress, * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments * @retval ::CA_STATUS_FAILED Operation failed */ -CAResult_t CAInitializeLEAdapter(const ca_thread_pool_t threadPool); +CAResult_t CAInitializeLEAdapter(); /** * Start the LE adapter layer. @@ -443,6 +443,25 @@ void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback); * adapter. */ void CASetBLEServerErrorHandleCallback(CABLEErrorHandleCallback callback); + +/** + * This is the callback which will be called whenever there is change in gatt connection + * with Client(Connected/Disconnected). + * + * @param[in] connected State of connection. + * @param[in] remoteAddress Mac address of the remote device in which we made connection. + */ +void CALEGattServerConnectionStateChanged(bool connected, const char *remoteAddress); + +/** + * This is the callback which will be called whenever there is change in gatt connection + * with server(Connected/Disconnected) + * + * @param[in] connected State of connection + * @param[in] remoteAddress Mac address of the remote device in which we made connection. + */ +void CALEGattConnectionStateChanged(bool connected, const char *remoteAddress); + #ifdef __cplusplus } #endif diff --git a/resource/csdk/connectivity/inc/canfcadapter.h b/resource/csdk/connectivity/inc/canfcadapter.h index 3e8fb48ee..3083ab38c 100644 --- a/resource/csdk/connectivity/inc/canfcadapter.h +++ b/resource/csdk/connectivity/inc/canfcadapter.h @@ -49,7 +49,7 @@ extern "C" */
CAResult_t CAInitializeNFC(CARegisterConnectivityCallback registerCallback,
CANetworkPacketReceivedCallback networkPacketCallback,
- CANetworkChangeCallback netCallback,
+ CAAdapterChangeCallback netCallback,
CAErrorHandleCallback errorCallback, ca_thread_pool_t handle);
/**
diff --git a/resource/csdk/connectivity/inc/caraadapter.h b/resource/csdk/connectivity/inc/caraadapter.h index 7dd094096..ed730f00e 100644 --- a/resource/csdk/connectivity/inc/caraadapter.h +++ b/resource/csdk/connectivity/inc/caraadapter.h @@ -51,7 +51,7 @@ extern "C" */ CAResult_t CAInitializeRA(CARegisterConnectivityCallback registerCallback, CANetworkPacketReceivedCallback networkPacketCallback, - CANetworkChangeCallback netCallback, + CAAdapterChangeCallback netCallback, ca_thread_pool_t handle); diff --git a/resource/csdk/connectivity/inc/catcpadapter.h b/resource/csdk/connectivity/inc/catcpadapter.h index 2528df131..e3da36916 100644 --- a/resource/csdk/connectivity/inc/catcpadapter.h +++ b/resource/csdk/connectivity/inc/catcpadapter.h @@ -54,7 +54,9 @@ typedef struct * @param[in] networkPacketCallback Callback to notify request and * response messages from server(s) * started at Connectivity Abstraction Layer. - * @param[in] netCallback Callback to notify the network additions + * @param[in] netCallback Callback to notify the adapter changes + * to Connectivity Abstraction Layer. + * @param[in] connCallback Callback to notify the connection changes * to Connectivity Abstraction Layer. * @param[in] errorCallback Callback to notify the network errors to * Connectivity Abstraction Layer. @@ -63,7 +65,8 @@ typedef struct */ CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback, CANetworkPacketReceivedCallback networkPacketCallback, - CANetworkChangeCallback netCallback, + CAAdapterChangeCallback netCallback, + CAConnectionChangeCallback connCallback, CAErrorHandleCallback errorCallback, ca_thread_pool_t handle); /** @@ -152,13 +155,11 @@ CAResult_t CAStopTCP(); void CATerminateTCP(); /** - * Set connected callback and disconnected callback to process KeepAlive. + * Set connection status changes callback to process KeepAlive. * connection informations are delivered these callbacks. - * @param[in] ConnHandler Connected callback. - * @param[in] DisconnHandler Disconnected Callback. + * @param[in] ConnHandler Connection status changes callback. */ -void CATCPSetKeepAliveCallbacks(CAKeepAliveConnectedCallback ConnHandler, - CAKeepAliveDisconnectedCallback DisconnHandler); +void CATCPSetKeepAliveCallbacks(CAKeepAliveConnectionCallback ConnHandler); #ifdef __cplusplus } /* extern "C" */ diff --git a/resource/csdk/connectivity/inc/catcpinterface.h b/resource/csdk/connectivity/inc/catcpinterface.h index 38efb008d..c3c25dbd2 100644 --- a/resource/csdk/connectivity/inc/catcpinterface.h +++ b/resource/csdk/connectivity/inc/catcpinterface.h @@ -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 (*CATCPKeepAliveHandleCallback)(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. @@ -86,7 +85,7 @@ void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback); * @param[in] keepaliveHandler Callback function to notify the connection information. * in the TCP adapter. */ -void CATCPSetKeepAliveCallback(CATCPKeepAliveHandleCallback keepaliveHandler); +void CATCPSetKeepAliveCallback(CAKeepAliveConnectionCallback keepaliveHandler); /** * Start TCP server. diff --git a/resource/csdk/connectivity/inc/pkix/crypto_adapter.h b/resource/csdk/connectivity/inc/pkix/crypto_adapter.h index 3f2b93cfb..bef054c06 100644 --- a/resource/csdk/connectivity/inc/pkix/crypto_adapter.h +++ b/resource/csdk/connectivity/inc/pkix/crypto_adapter.h @@ -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) diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.c index 1da403437..e979010d2 100644 --- a/resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.c +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.c @@ -275,7 +275,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; } diff --git a/resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c b/resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c index 8caf45fa2..566a9f3bd 100644 --- a/resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c +++ b/resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c @@ -71,10 +71,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 @@ -554,14 +554,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 +838,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 +1013,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 +1027,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() diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.c b/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.c index 16e588a82..5116fe92f 100644 --- a/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.c +++ b/resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.c @@ -488,6 +488,7 @@ void CAEDRTerminate() if (g_context) { (*env)->DeleteGlobalRef(env, g_context); + g_context = NULL; } CAEDRNativeSocketCloseToAll(env); diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/caedradapter.c b/resource/csdk/connectivity/src/bt_edr_adapter/caedradapter.c index 9a1c018bc..fb036ed3b 100644 --- a/resource/csdk/connectivity/src/bt_edr_adapter/caedradapter.c +++ b/resource/csdk/connectivity/src/bt_edr_adapter/caedradapter.c @@ -35,63 +35,53 @@ #include "pdu.h" /** - * @var EDR_ADAPTER_TAG - * @brief Logging tag for module name. + * Logging tag for module name. */ #define EDR_ADAPTER_TAG "OIC_CA_EDR_ADAP" /** - * @var g_edrThreadPool - * @brief Reference to threadpool. + * Reference to threadpool. */ static ca_thread_pool_t g_edrThreadPool = NULL; /** - * @var g_sendQueueHandle - * @brief Queue handle for Send Data + * Queue handle for Send Data */ static CAQueueingThread_t *g_sendQueueHandle = NULL; /** - * @var g_recvQueueHandle - * @brief Queue handle for Receive Data + * Queue handle for Receive Data */ static CAQueueingThread_t *g_recvQueueHandle = NULL; /** - * @var g_adapterState - * @brief Storing Adapter state information + * Storing Adapter state information */ static bool g_adapterState = true; /** - * @var g_networkPacketReceivedCallback - * @brief Maintains the callback to be notified on receival of network packets from other - * Bluetooth devices. + * Maintains the callback to be notified on receival of network packets from other + * Bluetooth devices. */ static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL; /** - * @var g_networkChangeCallback - * @brief Maintains the callback to be notified on local bluetooth adapter status change. + * Maintains the callback to be notified on local bluetooth adapter status change. */ -static CANetworkChangeCallback g_networkChangeCallback = NULL; +static CAAdapterChangeCallback g_adapterChangeCallback = NULL; /** - * @var g_errorCallback - * @brief error Callback to CA adapter + * error Callback to CA adapter */ static CAErrorHandleCallback g_errorCallback = NULL; /** - * @var g_localConnectivity - * @brief Information of local Bluetooth adapter. + * Information of local Bluetooth adapter. */ static CAEndpoint_t *g_localConnectivity = NULL; /** - * @var g_serverState - * @brief Storing Rfcommserver state information + * Storing Rfcommserver state information */ static bool g_serverState = false; @@ -139,21 +129,21 @@ static void CAEDRErrorHandler(const char *remoteAddress, const uint8_t *data, CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback, CANetworkPacketReceivedCallback packetReceivedCallback, - CANetworkChangeCallback networkStateChangeCallback, + CAAdapterChangeCallback netCallback, + CAConnectionChangeCallback connCallback, CAErrorHandleCallback errorCallback, ca_thread_pool_t handle) { // Input validation VERIFY_NON_NULL(registerCallback, EDR_ADAPTER_TAG, "register callback is NULL"); VERIFY_NON_NULL(packetReceivedCallback, EDR_ADAPTER_TAG, "data receive callback is NULL"); - VERIFY_NON_NULL(networkStateChangeCallback, EDR_ADAPTER_TAG, - "network state change callback is NULL"); + VERIFY_NON_NULL(netCallback, EDR_ADAPTER_TAG, "adapter state change callback is NULL"); + VERIFY_NON_NULL(connCallback, EDR_ADAPTER_TAG, "connection state change callback is NULL"); VERIFY_NON_NULL(handle, EDR_ADAPTER_TAG, "Thread pool handle is NULL"); // Register the callbacks - g_edrThreadPool = handle; g_networkPacketReceivedCallback = packetReceivedCallback; - g_networkChangeCallback = networkStateChangeCallback; + g_adapterChangeCallback = netCallback; g_errorCallback = errorCallback; // Initialize EDR Network Monitor @@ -385,7 +375,7 @@ void CATerminateEDR() CAAdapterTerminateQueues(); g_networkPacketReceivedCallback = NULL; - g_networkChangeCallback = NULL; + g_adapterChangeCallback = NULL; // Terminate thread pool g_edrThreadPool = NULL; @@ -778,7 +768,7 @@ void CAEDRNotifyNetworkStatus(CANetworkStatus_t status) } // Notify to upper layer - if (g_networkChangeCallback && g_localConnectivity && g_edrThreadPool) + if (g_adapterChangeCallback && g_localConnectivity && g_edrThreadPool) { // Add notification task to thread pool CAEDRNetworkEvent *event = CAEDRCreateNetworkEvent(g_localConnectivity, status); @@ -805,9 +795,9 @@ void CAEDROnNetworkStatusChanged(void *context) CAEDRNetworkEvent *networkEvent = (CAEDRNetworkEvent *) context; // Notify to upper layer - if (g_networkChangeCallback) + if (g_adapterChangeCallback) { - g_networkChangeCallback(networkEvent->info, networkEvent->status); + g_adapterChangeCallback(networkEvent->info->adapter, networkEvent->status); } // Free the created Network event diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/linux/SConscript b/resource/csdk/connectivity/src/bt_edr_adapter/linux/SConscript deleted file mode 100644 index 0e0996773..000000000 --- a/resource/csdk/connectivity/src/bt_edr_adapter/linux/SConscript +++ /dev/null @@ -1,9 +0,0 @@ -########################################## -# Build BT EDR adapter for Linux -########################################## - -Import('env') - -src_files = [ 'caedradapter.c'] - -Return('src_files') diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/linux/caedradapter.c b/resource/csdk/connectivity/src/bt_edr_adapter/linux/caedradapter.c deleted file mode 100644 index 4863861f9..000000000 --- a/resource/csdk/connectivity/src/bt_edr_adapter/linux/caedradapter.c +++ /dev/null @@ -1,141 +0,0 @@ -/****************************************************************** - * - * Copyright 2014 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include "caedradapter.h" -#include "logger.h" - -#define TAG PCF("OIC_CA") - -static CANetworkPacketReceivedCallback g_edrReceivedCallback = NULL; -static ca_thread_pool_t g_threadPoolHandle = NULL; - -CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback, - CANetworkPacketReceivedCallback reqRespCallback, - CANetworkChangeCallback networkStateChangeCallback, - CAErrorHandleCallback errorCallback, ca_thread_pool_t handle) -{ - (void)networkStateChangeCallback; - (void)errorCallback; - OIC_LOG(DEBUG, TAG, "CAInitializeEDR"); - - g_edrReceivedCallback = reqRespCallback; - g_threadPoolHandle = handle; - - // register handlers - CAConnectivityHandler_t handler = { - .startAdapter = CAStartEDR, - .startListenServer = CAStartEDRListeningServer, - .stopListenServer = CAStopEDRListeningServer, - .startDiscoveryServer = CAStartEDRDiscoveryServer, - .sendData = CASendEDRUnicastData, - .sendDataToAll = CASendEDRMulticastData, - .GetnetInfo = CAGetEDRInterfaceInformation, - .readData = CAReadEDRData, - .stopAdapter = CAStopEDR, - .terminate = CATerminateEDR, - .cType = CA_ADAPTER_RFCOMM_BTEDR - }; - - registerCallback(handler); - - return CA_STATUS_OK; -} - -CAResult_t CAStartEDR() -{ - OIC_LOG(DEBUG, TAG, "CAStartEDR"); - - return CA_STATUS_OK; -} - -CAResult_t CAStartEDRListeningServer() -{ - OIC_LOG(DEBUG, TAG, "CAStartEDRListeningServer"); - - return CA_STATUS_OK; -} - -CAResult_t CAStopEDRListeningServer() -{ - OIC_LOG(DEBUG, TAG, "CAStopEDRListeningServer"); - - return CA_STATUS_OK; -} - -CAResult_t CAStartEDRDiscoveryServer() -{ - OIC_LOG(DEBUG, TAG, "CAStartEDRDiscoveryServer"); - - return CA_STATUS_OK; -} - -int32_t CASendEDRUnicastData(const CAEndpoint_t *endpoint, const void *data, - uint32_t dataLen) -{ - (void)endpoint; - (void)data; - (void)dataLen; - OIC_LOG(DEBUG, TAG, "CASendEDRUnicastData"); - - return -1; -} - -int32_t CASendEDRMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen) -{ - (void)endpoint; - (void)data; - (void)dataLen; - OIC_LOG(DEBUG, TAG, "CASendEDRMulticastData"); - - return -1; -} - -CAResult_t CAGetEDRInterfaceInformation(CAEndpoint_t **info, uint32_t *size) -{ - (void)info; - (void)size; - OIC_LOG(DEBUG, TAG, "CAGetEDRInterfaceInformation"); - - return CA_STATUS_OK; -} - -CAResult_t CAReadEDRData() -{ - OIC_LOG(DEBUG, TAG, "Read EDR Data"); - - return CA_STATUS_OK; -} - -CAResult_t CAStopEDR() -{ - OIC_LOG(DEBUG, TAG, "CAStopEDR"); - - return CA_STATUS_OK; -} - -void CATerminateEDR() -{ - OIC_LOG(DEBUG, TAG, "CATerminateEDR"); -} - diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrnwmonitor.c b/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrnwmonitor.c index 4958b431e..3e7010703 100644 --- a/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrnwmonitor.c +++ b/resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrnwmonitor.c @@ -24,7 +24,6 @@ * This file provides the APIs for EDR Network Monitor. */ -#include <glib.h> #include <string.h> #include <bluetooth.h> @@ -35,9 +34,6 @@ #include "caqueueingthread.h" #include "caremotehandler.h" -static GMainLoop *g_mainloop = NULL; -static ca_thread_pool_t g_threadPoolHandle = NULL; - /** * @var g_edrNetworkChangeCallback * @brief Maintains the callback to be notified on local bluetooth adapter status change. @@ -51,27 +47,18 @@ static CAEDRNetworkStatusCallback g_edrNetworkChangeCallback = NULL; static void CAEDRAdapterStateChangeCallback(int result, bt_adapter_state_e adapterState, void *userData); -void CAEDRMainLoopThread(void *param) -{ - g_main_loop_run(g_mainloop); -} - CAResult_t CAEDRInitializeNetworkMonitor(const ca_thread_pool_t threadPool) { - OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN"); - g_threadPoolHandle = threadPool; - OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT"); + (void)threadPool; return CA_STATUS_OK; } -void CAEDRTerminateNetworkMonitor(void) +void CAEDRTerminateNetworkMonitor() { OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN"); g_edrNetworkChangeCallback = NULL; - // Terminate Bluetooth service - bt_deinitialize(); OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT"); } @@ -80,33 +67,20 @@ CAResult_t CAEDRStartNetworkMonitor() { OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN"); - g_mainloop = g_main_loop_new(NULL, 0); - if(!g_mainloop) - { - OIC_LOG(ERROR, EDR_ADAPTER_TAG, "g_main_loop_new failed\n"); - return CA_STATUS_FAILED; - } - - if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, CAEDRMainLoopThread, (void *) NULL)) - { - OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create thread!"); - return CA_STATUS_FAILED; - } - // Initialize Bluetooth service - int err = bt_initialize(); - if (BT_ERROR_NONE != err) + int ret = bt_initialize(); + if (BT_ERROR_NONE != ret) { OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth initialization failed!, error num [%x]", - err); - return CA_STATUS_FAILED; + ret); + return; } - int ret = bt_adapter_set_state_changed_cb(CAEDRAdapterStateChangeCallback, NULL); + 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 CA_STATUS_FAILED; + return; } OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT"); @@ -124,10 +98,13 @@ CAResult_t CAEDRStopNetworkMonitor() return CA_STATUS_FAILED; } - if (g_mainloop) + ret = bt_deinitialize(); + if (BT_ERROR_NONE != ret) { - g_main_loop_quit(g_mainloop); + OIC_LOG(ERROR, EDR_ADAPTER_TAG, "bt_deinitialize failed"); + return CA_STATUS_FAILED; } + OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT"); return CA_STATUS_OK; } @@ -179,7 +156,6 @@ CAResult_t CAEDRGetAdapterEnableState(bool *state) // Input validation VERIFY_NON_NULL(state, EDR_ADAPTER_TAG, "state holder is NULL!"); - bt_adapter_state_e adapterState; int err = bt_adapter_get_state(&adapterState); // Get Bluetooth adapter state diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.c b/resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.c index dd953de66..0a542ed64 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.c +++ b/resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.c @@ -95,6 +95,7 @@ static ca_mutex g_deviceScanRetryDelayMutex = NULL; static ca_cond g_deviceScanRetryDelayCond = NULL; static ca_mutex g_scanMutex = NULL; +static ca_mutex g_threadSendStateMutex = NULL; static CABLEDataReceivedCallback g_CABLEClientDataReceivedCallback = NULL; @@ -781,12 +782,30 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t* { OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed"); ca_mutex_unlock(g_threadSendMutex); - return res; + return ret; } ca_mutex_unlock(g_threadSendMutex); OIC_LOG(INFO, TAG, "unicast - send logic has finished"); - return CALECheckSendState(address); + if (CALEClientIsValidState(address, CA_LE_SEND_STATE, + STATE_SEND_SUCCESS)) + { + ret = CA_STATUS_OK; + } + else + { + ret = CA_SEND_FAILED; + } + + // reset send state + ret = CALEClientUpdateDeviceState(address, CA_LE_SEND_STATE, + STATE_SEND_NONE); + if (CA_STATUS_OK != ret) + { + OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed"); + } + + return ret; // error label. error_exit: @@ -801,7 +820,7 @@ error_exit: { (*g_jvm)->DetachCurrentThread(g_jvm); } - return res; + return ret; } if (isAttached) @@ -809,10 +828,6 @@ error_exit: (*g_jvm)->DetachCurrentThread(g_jvm); } - if (g_clientErrorCallback) - { - g_clientErrorCallback(address, data, dataLen, CA_SEND_FAILED); - } ca_mutex_unlock(g_threadSendMutex); return CA_SEND_FAILED; } @@ -934,31 +949,6 @@ error_exit: return CA_SEND_FAILED; } -CAResult_t CALECheckSendState(const char* address) -{ - VERIFY_NON_NULL(address, TAG, "address is null"); - - ca_mutex_lock(g_deviceStateListMutex); - CALEState_t* state = CALEClientGetStateInfo(address); - if (NULL == state) - { - OIC_LOG(ERROR, TAG, "state is null"); - ca_mutex_unlock(g_deviceStateListMutex); - return CA_SEND_FAILED; - } - - if (STATE_SEND_SUCCESS != state->sendState) - { - OIC_LOG(ERROR, TAG, "sendstate is not STATE_SEND_SUCCESS"); - ca_mutex_unlock(g_deviceStateListMutex); - return CA_SEND_FAILED; - } - - OIC_LOG(INFO, TAG, "sendstate is STATE_SEND_SUCCESS"); - ca_mutex_unlock(g_deviceStateListMutex); - return CA_STATUS_OK; -} - CAResult_t CALEClientSendData(JNIEnv *env, jobject device) { OIC_LOG(DEBUG, TAG, "IN - CALEClientSendData"); @@ -981,7 +971,6 @@ CAResult_t CALEClientSendData(JNIEnv *env, jobject device) ca_mutex_lock(g_deviceStateListMutex); state = CALEClientGetStateInfo(address); ca_mutex_unlock(g_deviceStateListMutex); - (*env)->ReleaseStringUTFChars(env, jni_address, address); } if (!state) @@ -992,13 +981,6 @@ CAResult_t CALEClientSendData(JNIEnv *env, jobject device) // if there is gatt object in g_gattObjectList. if (jni_address) { - address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL); - if (!address) - { - OIC_LOG(ERROR, TAG, "address is not available"); - return CA_STATUS_FAILED; - } - jobject gatt = CALEClientGetGattObjInList(env, address); if (gatt) { @@ -1022,21 +1004,10 @@ CAResult_t CALEClientSendData(JNIEnv *env, jobject device) } else { - if (STATE_CONNECTED == state->connectedState) + if (CALEClientIsValidState(address, CA_LE_CONNECTION_STATE, + STATE_SERVICE_CONNECTED)) { OIC_LOG(INFO, TAG, "GATT has already connected"); - if (!jni_address) - { - OIC_LOG(ERROR, TAG, "jni_address is not available"); - return CA_STATUS_FAILED; - } - - address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL); - if (!address) - { - OIC_LOG(ERROR, TAG, "address is not available"); - return CA_STATUS_FAILED; - } jobject gatt = CALEClientGetGattObjInList(env, address); if (!gatt) @@ -1055,7 +1026,13 @@ CAResult_t CALEClientSendData(JNIEnv *env, jobject device) } (*env)->ReleaseStringUTFChars(env, jni_address, address); } - else + else if(CALEClientIsValidState(address, CA_LE_CONNECTION_STATE, + STATE_CONNECTED)) + { + OIC_LOG(INFO, TAG, "service connecting..."); + } + else if(CALEClientIsValidState(address, CA_LE_CONNECTION_STATE, + STATE_DISCONNECTED)) { OIC_LOG(INFO, TAG, "STATE_DISCONNECTED - start to connect LE"); @@ -1063,13 +1040,6 @@ CAResult_t CALEClientSendData(JNIEnv *env, jobject device) // if there is gatt object in g_gattObjectList. if (jni_address) { - address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL); - if (!address) - { - OIC_LOG(ERROR, TAG, "address is not available"); - return CA_STATUS_FAILED; - } - jobject gatt = CALEClientGetGattObjInList(env, address); if (gatt) { @@ -1084,7 +1054,8 @@ CAResult_t CALEClientSendData(JNIEnv *env, jobject device) OIC_LOG(DEBUG, TAG, "start to connect LE"); jobject gatt = CALEClientConnect(env, device, - CALEClientGetAutoConnectFlag(env, jni_address)); + CALEClientGetFlagFromState(env, jni_address, + CA_LE_AUTO_CONNECT_FLAG)); if (NULL == gatt) { OIC_LOG(ERROR, TAG, "CALEClientConnect has failed"); @@ -1514,9 +1485,10 @@ CAResult_t CALEClientStopScanImpl(JNIEnv *env, jobject callback) return CA_STATUS_OK; } -CAResult_t CALEClientSetAutoConnectFlag(JNIEnv *env, jstring jni_address, jboolean flag) +CAResult_t CALEClientSetFlagToState(JNIEnv *env, jstring jni_address, + jint state_idx, jboolean flag) { - OIC_LOG(DEBUG, TAG, "IN - CALEClientSetAutoConnectFlag"); + OIC_LOG(DEBUG, TAG, "IN - CALEClientSetFlagToState"); VERIFY_NON_NULL(env, TAG, "env"); VERIFY_NON_NULL(jni_address, TAG, "jni_address"); @@ -1539,20 +1511,27 @@ CAResult_t CALEClientSetAutoConnectFlag(JNIEnv *env, jstring jni_address, jboole ca_mutex_unlock(g_deviceStateListMutex); return CA_STATUS_FAILED; } - OIC_LOG_V(INFO, TAG, "auto connect flag is set %d", flag); + OIC_LOG_V(INFO, TAG, "%d flag is set : %d", state_idx, flag); - curState->autoConnectFlag = flag; + switch(state_idx) + { + case CA_LE_AUTO_CONNECT_FLAG: + curState->autoConnectFlag = flag; + break; + default: + break; + } } (*env)->ReleaseStringUTFChars(env, jni_address, address); ca_mutex_unlock(g_deviceStateListMutex); - OIC_LOG(DEBUG, TAG, "OUT - CALEClientSetAutoConnectFlag"); + OIC_LOG(DEBUG, TAG, "OUT - CALEClientSetFlagToState"); return CA_STATUS_OK; } -jboolean CALEClientGetAutoConnectFlag(JNIEnv *env, jstring jni_address) +jboolean CALEClientGetFlagFromState(JNIEnv *env, jstring jni_address, jint state_idx) { - OIC_LOG(DEBUG, TAG, "IN - CALEClientGetAutoConnectFlag"); + OIC_LOG(DEBUG, TAG, "IN - CALEClientGetFlagFromState"); VERIFY_NON_NULL_RET(env, TAG, "env", false); VERIFY_NON_NULL_RET(jni_address, TAG, "jni_address", false); @@ -1573,13 +1552,63 @@ jboolean CALEClientGetAutoConnectFlag(JNIEnv *env, jstring jni_address) ca_mutex_unlock(g_deviceStateListMutex); return JNI_FALSE; } - OIC_LOG_V(INFO, TAG, "auto connect flag is %d", curState->autoConnectFlag); + + jboolean ret = JNI_FALSE; + switch(state_idx) + { + case CA_LE_AUTO_CONNECT_FLAG: + ret = curState->autoConnectFlag; + break; + default: + break; + } + OIC_LOG_V(INFO, TAG, "%d flag is %d", state_idx, ret); (*env)->ReleaseStringUTFChars(env, jni_address, address); ca_mutex_unlock(g_deviceStateListMutex); - OIC_LOG(DEBUG, TAG, "OUT - CALEClientGetAutoConnectFlag"); - return curState->autoConnectFlag; + OIC_LOG(DEBUG, TAG, "OUT - CALEClientGetFlagFromState"); + return ret; +} + +CAResult_t CALEClientDirectConnect(JNIEnv *env, jobject bluetoothDevice, jboolean autoconnect) +{ + OIC_LOG(DEBUG, TAG, "CALEClientDirectConnect"); + VERIFY_NON_NULL(env, TAG, "env is null"); + VERIFY_NON_NULL(bluetoothDevice, TAG, "bluetoothDevice is null"); + + ca_mutex_lock(g_threadSendMutex); + + jstring jni_address = CALEGetAddressFromBTDevice(env, bluetoothDevice); + if (!jni_address) + { + OIC_LOG(ERROR, TAG, "jni_address is not available"); + ca_mutex_unlock(g_threadSendMutex); + return CA_STATUS_FAILED; + } + + const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL); + if (!address) + { + OIC_LOG(ERROR, TAG, "address is not available"); + ca_mutex_unlock(g_threadSendMutex); + return CA_STATUS_FAILED; + } + + CAResult_t res = CA_STATUS_OK; + if(CALEClientIsValidState(address, CA_LE_CONNECTION_STATE, + STATE_DISCONNECTED)) + { + jobject newGatt = CALEClientConnect(env, bluetoothDevice, autoconnect); + if (NULL == newGatt) + { + OIC_LOG(INFO, TAG, "newGatt is not available"); + res = CA_STATUS_FAILED; + } + } + ca_mutex_unlock(g_threadSendMutex); + + return res; } jobject CALEClientConnect(JNIEnv *env, jobject bluetoothDevice, jboolean autoconnect) @@ -1975,9 +2004,49 @@ static void CALEWriteCharacteristicThread(void* object) CAResult_t CALESetValueAndWriteCharacteristic(JNIEnv* env, jobject gatt) { + OIC_LOG(DEBUG, TAG, "CALESetValueAndWriteCharacteristic"); + VERIFY_NON_NULL(gatt, TAG, "gatt is null"); VERIFY_NON_NULL(env, TAG, "env is null"); + jstring jni_address = CALEClientGetAddressFromGattObj(env, gatt); + if (!jni_address) + { + CALEClientSendFinish(env, gatt); + return CA_STATUS_FAILED; + } + + const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL); + if (!address) + { + CALEClientSendFinish(env, gatt); + return CA_STATUS_FAILED; + } + + ca_mutex_lock(g_threadSendStateMutex); + + if (CALEClientIsValidState(address, CA_LE_SEND_STATE, STATE_SENDING)) + { + OIC_LOG(INFO, TAG, "current state is SENDING"); + (*env)->ReleaseStringUTFChars(env, jni_address, address); + ca_mutex_unlock(g_threadSendStateMutex); + return CA_STATUS_OK; + } + + if (CA_STATUS_OK != CALEClientUpdateDeviceState(address, CA_LE_SEND_STATE, + STATE_SENDING)) + { + OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed"); + (*env)->ReleaseStringUTFChars(env, jni_address, address); + CALEClientSendFinish(env, gatt); + ca_mutex_unlock(g_threadSendStateMutex); + return CA_STATUS_FAILED; + } + + (*env)->ReleaseStringUTFChars(env, jni_address, address); + + ca_mutex_unlock(g_threadSendStateMutex); + // send data jobject jni_obj_character = CALEClientCreateGattCharacteristic(env, gatt, g_sendBuffer); if (!jni_obj_character) @@ -3195,48 +3264,22 @@ jstring CALEClientGetLEAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice) * BT State List */ -CAResult_t CALEClientUpdateDeviceState(const char* address, uint32_t connectedState, - uint16_t notificationState, uint16_t sendState) +CAResult_t CALEClientUpdateDeviceState(const char* address, uint16_t state_type, + uint16_t target_state) { VERIFY_NON_NULL(address, TAG, "address is null"); - CALEState_t *newstate = (CALEState_t*) OICCalloc(1, sizeof(*newstate)); - if (!newstate) - { - OIC_LOG(ERROR, TAG, "out of memory"); - return CA_MEMORY_ALLOC_FAILED; - } - - if (strlen(address) > CA_MACADDR_SIZE) - { - OIC_LOG(ERROR, TAG, "address is not proper"); - OICFree(newstate); - return CA_STATUS_FAILED; - } - - OICStrcpy(newstate->address, sizeof(newstate->address), address); - newstate->connectedState = connectedState; - newstate->notificationState = notificationState; - newstate->sendState = sendState; - return CALEClientAddDeviceStateToList(newstate); -} - -CAResult_t CALEClientAddDeviceStateToList(CALEState_t* state) -{ - VERIFY_NON_NULL(state, TAG, "state is null"); - - ca_mutex_lock(g_deviceStateListMutex); - if (!g_deviceStateList) { OIC_LOG(ERROR, TAG, "gdevice_list is null"); - ca_mutex_unlock(g_deviceStateListMutex); return CA_STATUS_FAILED; } - if (CALEClientIsDeviceInList(state->address)) + ca_mutex_lock(g_deviceStateListMutex); + + if (CALEClientIsDeviceInList(address)) { - CALEState_t* curState = CALEClientGetStateInfo(state->address); + CALEState_t* curState = CALEClientGetStateInfo(address); if(!curState) { OIC_LOG(ERROR, TAG, "curState is null"); @@ -3244,27 +3287,63 @@ CAResult_t CALEClientAddDeviceStateToList(CALEState_t* state) return CA_STATUS_FAILED; } - if (STATE_CHARACTER_NO_CHANGE == state->notificationState) + switch(state_type) { - state->notificationState = curState->notificationState; + case CA_LE_CONNECTION_STATE: + curState->connectedState = target_state; + break; + case CA_LE_SEND_STATE: + curState->sendState = target_state; + break; + default: + break; + } + OIC_LOG_V(INFO, TAG, "update state : - addr : %s, " + "conn : %d, send : %d, ACFlag : %d", + curState->address, curState->connectedState, + curState->sendState, curState->autoConnectFlag); + } + else /** state is added newly **/ + { + if (strlen(address) > CA_MACADDR_SIZE) + { + OIC_LOG(ERROR, TAG, "address is not proper"); + ca_mutex_unlock(g_deviceStateListMutex); + return CA_STATUS_INVALID_PARAM; } - state->autoConnectFlag = curState->autoConnectFlag; - // delete previous state for update new state - CAResult_t res = CALEClientRemoveDeviceState(state->address); - if (CA_STATUS_OK != res) + CALEState_t *newstate = (CALEState_t*) OICCalloc(1, sizeof(*newstate)); + if (!newstate) { - OIC_LOG(ERROR, TAG, "CALEClientRemoveDeviceState has failed"); + OIC_LOG(ERROR, TAG, "out of memory"); ca_mutex_unlock(g_deviceStateListMutex); - return res; + return CA_MEMORY_ALLOC_FAILED; } + + OICStrcpy(newstate->address, sizeof(newstate->address), address); + + switch(state_type) + { + case CA_LE_CONNECTION_STATE: + newstate->connectedState = target_state; + newstate->sendState = STATE_SEND_NONE; + break; + case CA_LE_SEND_STATE: + newstate->connectedState = STATE_DISCONNECTED; + newstate->sendState = target_state; + break; + default: + break; + } + OIC_LOG_V(INFO, TAG, "Set newState to List - addr : %s, " + "conn : %d, send : %d, ACFlag : %d", + newstate->address, newstate->connectedState, + newstate->sendState, newstate->autoConnectFlag); + u_arraylist_add(g_deviceStateList, newstate); // update new state } - u_arraylist_add(g_deviceStateList, state); // update new state - OIC_LOG_V(INFO, TAG, "Set State Info to List : %d, %d, %s, %d", - state->connectedState, state->notificationState, - state->address, state->autoConnectFlag); ca_mutex_unlock(g_deviceStateListMutex); + return CA_STATUS_OK; } @@ -3359,7 +3438,6 @@ CAResult_t CALEClientResetDeviceStateForAll() // autoConnectFlag value will be not changed, // since it has reset only termination case. state->connectedState = STATE_DISCONNECTED; - state->notificationState = STATE_CHARACTER_UNSET; state->sendState = STATE_SEND_NONE; } ca_mutex_unlock(g_deviceStateListMutex); @@ -3410,7 +3488,6 @@ CAResult_t CALEClientRemoveDeviceState(const char* remoteAddress) CALEState_t* CALEClientGetStateInfo(const char* remoteAddress) { - OIC_LOG(DEBUG, TAG, "CALEClientGetStateInfo"); VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", NULL); if (!g_deviceStateList) @@ -3420,7 +3497,7 @@ CALEState_t* CALEClientGetStateInfo(const char* remoteAddress) } uint32_t length = u_arraylist_length(g_deviceStateList); - OIC_LOG_V(DEBUG, TAG, "CALEClientGetStateInfo : %d", length); + OIC_LOG_V(DEBUG, TAG, "size of deviceStateList is %d", length); for (uint32_t index = 0; index < length; index++) { @@ -3443,9 +3520,11 @@ CALEState_t* CALEClientGetStateInfo(const char* remoteAddress) return NULL; } -bool CALEClientIsConnectedDevice(const char* remoteAddress) +bool CALEClientIsValidState(const char* remoteAddress, uint16_t state_type, + uint16_t target_state) { - OIC_LOG(DEBUG, TAG, "CALEClientIsConnectedDevice"); + OIC_LOG_V(DEBUG, TAG, "CALEClientIsValidState : type[%d], target state[%d]", + state_type, target_state); VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", false); ca_mutex_lock(g_deviceStateListMutex); @@ -3456,74 +3535,36 @@ bool CALEClientIsConnectedDevice(const char* remoteAddress) return false; } - uint32_t length = u_arraylist_length(g_deviceStateList); - for (uint32_t index = 0; index < length; index++) + CALEState_t* state = CALEClientGetStateInfo(remoteAddress); + if (NULL == state) { - CALEState_t* state = (CALEState_t*) u_arraylist_get(g_deviceStateList, index); - if (!state) - { - OIC_LOG(ERROR, TAG, "CALEState_t object is null"); - continue; - } - - if (!strcmp(state->address, remoteAddress)) - { - OIC_LOG(DEBUG, TAG, "check whether it is connected or not"); - - if (STATE_CONNECTED == state->connectedState) - { - ca_mutex_unlock(g_deviceStateListMutex); - return true; - } - else - { - ca_mutex_unlock(g_deviceStateListMutex); - return false; - } - } + OIC_LOG(ERROR, TAG, "state is null"); + ca_mutex_unlock(g_deviceStateListMutex); + return false; } - ca_mutex_unlock(g_deviceStateListMutex); - return false; -} -bool CALEClientIsSetCharacteristic(const char* remoteAddress) -{ - OIC_LOG(DEBUG, TAG, "CALEClientIsSetCharacteristic"); - VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", false); + uint16_t curValue = 0; + switch(state_type) + { + case CA_LE_CONNECTION_STATE: + curValue = state->connectedState; + break; + case CA_LE_SEND_STATE: + curValue = state->sendState; + break; + default: + break; + } - ca_mutex_lock(g_deviceStateListMutex); - if (!g_deviceStateList) + if (target_state == curValue) { - OIC_LOG(ERROR, TAG, "g_deviceStateList is null"); ca_mutex_unlock(g_deviceStateListMutex); - return false; + return true; } - - uint32_t length = u_arraylist_length(g_deviceStateList); - for (uint32_t index = 0; index < length; index++) + else { - CALEState_t* state = (CALEState_t*) u_arraylist_get(g_deviceStateList, index); - if (!state) - { - OIC_LOG(ERROR, TAG, "CALEState_t object is null"); - continue; - } - - if (!strcmp(state->address, remoteAddress)) - { - OIC_LOG_V(DEBUG, TAG, "check whether it was set or not:%d", state->notificationState); - - if (STATE_CHARACTER_SET == state->notificationState) - { - ca_mutex_unlock(g_deviceStateListMutex); - return true; - } - else - { - ca_mutex_unlock(g_deviceStateListMutex); - return false; - } - } + ca_mutex_unlock(g_deviceStateListMutex); + return false; } ca_mutex_unlock(g_deviceStateListMutex); @@ -3702,6 +3743,16 @@ CAResult_t CALEClientInitGattMutexVaraibles() } } + if (NULL == g_threadSendStateMutex) + { + g_threadSendStateMutex = ca_mutex_new(); + if (NULL == g_threadSendStateMutex) + { + OIC_LOG(ERROR, TAG, "ca_mutex_new has failed"); + return CA_STATUS_FAILED; + } + } + return CA_STATUS_OK; } @@ -3733,6 +3784,9 @@ void CALEClientTerminateGattMutexVariables() ca_mutex_free(g_deviceScanRetryDelayMutex); g_deviceScanRetryDelayMutex = NULL; + + ca_mutex_free(g_threadSendStateMutex); + g_threadSendStateMutex = NULL; } void CALEClientSetSendFinishFlag(bool flag) @@ -4011,9 +4065,8 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattConnectionStateChangeCallback(J const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL); if (address) { - CAResult_t res = CALEClientUpdateDeviceState(address, STATE_CONNECTED, - STATE_CHARACTER_NO_CHANGE, - STATE_SEND_NONE); + CAResult_t res = CALEClientUpdateDeviceState(address, CA_LE_CONNECTION_STATE, + STATE_CONNECTED); if (CA_STATUS_OK != res) { OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed"); @@ -4051,9 +4104,8 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattConnectionStateChangeCallback(J const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL); if (address) { - CAResult_t res = CALEClientUpdateDeviceState(address, STATE_DISCONNECTED, - STATE_CHARACTER_UNSET, - STATE_SEND_NONE); + CAResult_t res = CALEClientUpdateDeviceState(address, CA_LE_CONNECTION_STATE, + STATE_DISCONNECTED); if (CA_STATUS_OK != res) { OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed"); @@ -4169,55 +4221,41 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattServicesDiscoveredCallback(JNIE return; } - if (!CALEClientIsSetCharacteristic(address)) + jstring jni_uuid = (*env)->NewStringUTF(env, OIC_GATT_CHARACTERISTIC_RESPONSE_UUID); + if (!jni_uuid) { - jstring jni_uuid = (*env)->NewStringUTF(env, OIC_GATT_CHARACTERISTIC_RESPONSE_UUID); - if (!jni_uuid) - { - OIC_LOG(ERROR, TAG, "jni_uuid is null"); - goto error_exit; - } + OIC_LOG(ERROR, TAG, "jni_uuid is null"); + goto error_exit; + } - jobject jni_obj_GattCharacteristic = CALEClientGetGattService(env, gatt, jni_uuid); - if (!jni_obj_GattCharacteristic) - { - OIC_LOG(ERROR, TAG, "jni_obj_GattCharacteristic is null"); - goto error_exit; - } + jobject jni_obj_GattCharacteristic = CALEClientGetGattService(env, gatt, jni_uuid); + if (!jni_obj_GattCharacteristic) + { + OIC_LOG(ERROR, TAG, "jni_obj_GattCharacteristic is null"); + goto error_exit; + } - CAResult_t res = CALEClientSetCharacteristicNotification(env, gatt, - jni_obj_GattCharacteristic); - if (CA_STATUS_OK != res) - { - OIC_LOG(ERROR, TAG, "CALEClientSetCharacteristicNotification has failed"); - goto error_exit; - } + CAResult_t res = CALEClientSetCharacteristicNotification(env, gatt, + jni_obj_GattCharacteristic); + if (CA_STATUS_OK != res) + { + OIC_LOG(ERROR, TAG, "CALEClientSetCharacteristicNotification has failed"); + goto error_exit; + } - res = CALEClientSetUUIDToDescriptor(env, gatt, jni_obj_GattCharacteristic); - if (CA_STATUS_OK != res) - { - OIC_LOG_V(INFO, TAG, "Descriptor is not found : %d", res); - if (g_sendBuffer) - { - CAResult_t res = CALEClientWriteCharacteristic(env, gatt); - if (CA_STATUS_OK != res) - { - OIC_LOG(ERROR, TAG, "CALEClientWriteCharacteristic has failed"); - goto error_exit; - } - } - } + res = CALEClientSetUUIDToDescriptor(env, gatt, jni_obj_GattCharacteristic); + if (CA_STATUS_OK != res) + { + OIC_LOG_V(INFO, TAG, "Descriptor is not found : %d", res); - res = CALEClientUpdateDeviceState(address, STATE_CONNECTED, STATE_CHARACTER_SET, - STATE_SEND_NONE); + res = CALEClientUpdateDeviceState(address, CA_LE_CONNECTION_STATE , + STATE_SERVICE_CONNECTED); if (CA_STATUS_OK != res) { OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed"); goto error_exit; } - } - else - { + if (g_sendBuffer) { CAResult_t res = CALEClientWriteCharacteristic(env, gatt); @@ -4228,6 +4266,7 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattServicesDiscoveredCallback(JNIE } } } + OIC_LOG(INFO, TAG, "ServicesDiscovery is successful"); (*env)->ReleaseStringUTFChars(env, jni_address, address); return; @@ -4283,9 +4322,8 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattCharacteristicWriteCallback( ca_cond_signal(g_threadWriteCharacteristicCond); ca_mutex_unlock(g_threadWriteCharacteristicMutex); - CAResult_t res = CALEClientUpdateDeviceState(address, STATE_CONNECTED, - STATE_CHARACTER_SET, - STATE_SEND_FAILED); + CAResult_t res = CALEClientUpdateDeviceState(address, CA_LE_SEND_STATE, + STATE_SEND_FAIL); if (CA_STATUS_OK != res) { OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed"); @@ -4304,7 +4342,7 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattCharacteristicWriteCallback( else { OIC_LOG(DEBUG, TAG, "send success"); - CAResult_t res = CALEClientUpdateDeviceState(address, STATE_CONNECTED, STATE_CHARACTER_SET, + CAResult_t res = CALEClientUpdateDeviceState(address, CA_LE_SEND_STATE, STATE_SEND_SUCCESS); if (CA_STATUS_OK != res) { @@ -4413,6 +4451,26 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattDescriptorWriteCallback(JNIEnv goto error_exit; } + jstring jni_address = CALEClientGetAddressFromGattObj(env, gatt); + if (!jni_address) + { + goto error_exit; + } + + const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL); + if (address) + { + CAResult_t res = CALEClientUpdateDeviceState(address, CA_LE_CONNECTION_STATE, + STATE_SERVICE_CONNECTED); + if (CA_STATUS_OK != res) + { + OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed"); + (*env)->ReleaseStringUTFChars(env, jni_address, address); + goto error_exit; + } + } + (*env)->ReleaseStringUTFChars(env, jni_address, address); + if (g_sendBuffer) { CAResult_t res = CALEClientWriteCharacteristic(env, gatt); diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.h b/resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.h index 10066e1e5..3dc64f6ca 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.h +++ b/resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.h @@ -37,19 +37,15 @@ extern "C" static const uint16_t GATT_ERROR = 133; -static const uint16_t STATE_CHARACTER_SET = 2; -static const uint16_t STATE_CHARACTER_UNSET = 1; -static const uint16_t STATE_CHARACTER_NO_CHANGE = 0; - -static const uint16_t STATE_SEND_NONE = 0; -static const uint16_t STATE_SEND_SUCCESS = 1; -static const uint16_t STATE_SEND_FAILED = 2; +static const uint16_t STATE_SEND_NONE = 1; +static const uint16_t STATE_SEND_SUCCESS = 2; +static const uint16_t STATE_SEND_FAIL = 3; +static const uint16_t STATE_SENDING = 4; typedef struct le_state_info { char address[CA_MACADDR_SIZE]; - jint connectedState; - uint16_t notificationState; + uint16_t connectedState; uint16_t sendState; jboolean autoConnectFlag; } CALEState_t; @@ -180,13 +176,6 @@ CAResult_t CALEClientSendMulticastMessageImpl(JNIEnv *env, const uint8_t *data, const uint32_t dataLen); /** - * check whether it is connected or not with remote address. - * @param[in] address remote address. - * @return ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h). - */ -CAResult_t CALECheckSendState(const char* address); - -/** * send data to remote device. * if it isn't connected yet. connect LE before try to send data. * @param[in] env JNI interface pointer. @@ -272,20 +261,23 @@ void CALEClientSetScanFlag(bool flag); CAResult_t CALEClientStopScanImpl(JNIEnv *env, jobject callback); /** - * set auto connect flag for connectGatt API. + * set flag into State List. * @param[in] env JNI interface pointer. * @param[in] jni_address remote address. + * @param[in] state_idx state index. * @param[in] flag auto connect flag. */ -CAResult_t CALEClientSetAutoConnectFlag(JNIEnv *env, jstring jni_address, jboolean flag); +CAResult_t CALEClientSetFlagToState(JNIEnv *env, jstring jni_address, + jint state_idx, jboolean flag); /** - * get auto connect flag. + * get flag from State List. * @param[in] env JNI interface pointer. * @param[in] jni_address remote address. - * @return current auto connect flag; + * @param[in] state_idx state index. + * @return current flag; */ -jboolean CALEClientGetAutoConnectFlag(JNIEnv *env, jstring jni_address); +jboolean CALEClientGetFlagFromState(JNIEnv *env, jstring jni_address, jint state_idx); /** * connect to gatt server hosted. @@ -505,20 +497,12 @@ jstring CALEClientGetLEAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice) /** * update new state information. * @param[in] address remote address. - * @param[in] connectedState connection state. - * @param[in] notificationState whether characteristic notification already set or not. - * @param[in] sendState whether sending was success or not. + * @param[in] state_type state type. + * @param[in] target_state state index to update. * @return ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h). */ -CAResult_t CALEClientUpdateDeviceState(const char* address, uint32_t connectedState, - uint16_t notificationState, uint16_t sendState); - -/** - * add new state to state list. - * @param[in] state new state. - * @return ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h). - */ -CAResult_t CALEClientAddDeviceStateToList(CALEState_t* state); +CAResult_t CALEClientUpdateDeviceState(const char* address, uint16_t state_type, + uint16_t target_state); /** * check whether the remote address is existed or not. @@ -555,18 +539,14 @@ CAResult_t CALEClientRemoveDeviceState(const char* remoteAddress); CALEState_t* CALEClientGetStateInfo(const char* remoteAddress); /** - * check whether the remote address is connected or not. - * @param[in] remoteAddress remote address. - * @return true or false. - */ -bool CALEClientIsConnectedDevice(const char* remoteAddress); - -/** - * check whether the remote address set CharacteristicNotification or not. + * check whether the remote address has same state with target state. * @param[in] remoteAddress remote address. + * @param[in] state_type state_type. + * @param[in] target_state state index to check. * @return true or false. */ -bool CALEClientIsSetCharacteristic(const char* remoteAddress); +bool CALEClientIsValidState(const char* remoteAddress, uint16_t state_type, + uint16_t target_state); /** * create scan device list. @@ -613,6 +593,15 @@ CAResult_t CALEClientCloseProfileProxy(JNIEnv *env, jobject gatt); */ jobject CALEClientGattConnect(JNIEnv *env, jobject bluetoothDevice, jboolean autoconnect); +/** + * connect to GATT Server hosted by this device directly. + * @param[in] env JNI interface pointer. + * @param[in] bluetoothDevice bluetooth device object. + * @param[in] autoconnect connect as soon as the device becomes avaiable(true). + * @return ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h). + */ +CAResult_t CALEClientDirectConnect(JNIEnv *env, jobject bluetoothDevice, jboolean autoconnect); + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.c b/resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.c index 758243e0f..099d6ec7e 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.c +++ b/resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.c @@ -83,11 +83,10 @@ void CALESetAdapterStateCallback(CALEDeviceStateChangedCallback callback) g_bleDeviceStateChangedCallback = callback; } -CAResult_t CAInitializeLEAdapter(const ca_thread_pool_t threadPool) +CAResult_t CAInitializeLEAdapter() { - OIC_LOG(DEBUG, TAG, "IN"); - (void)threadPool; - OIC_LOG(DEBUG, TAG, "OUT"); + // Nothing to do. + return CA_STATUS_OK; } diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.c b/resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.c index 2905742b9..7a76dbc31 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.c +++ b/resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.c @@ -373,8 +373,6 @@ jstring CALEGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice) jint CALEGetConstantsValue(JNIEnv *env, const char* classType, const char* name) { - OIC_LOG(DEBUG, TAG, "CALEGetConstantsValue"); - VERIFY_NON_NULL_RET(env, TAG, "env", -1); VERIFY_NON_NULL_RET(classType, TAG, "classType", -1); VERIFY_NON_NULL_RET(name, TAG, "name", -1); diff --git a/resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.h b/resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.h index dcb1b0481..7f3e312e8 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.h +++ b/resource/csdk/connectivity/src/bt_le_adapter/android/caleutils.h @@ -36,6 +36,10 @@ extern "C" { #endif +#define CA_LE_AUTO_CONNECT_FLAG 1 +#define CA_LE_CONNECTION_STATE 2 +#define CA_LE_SEND_STATE 3 + /* Service UUID */ static const char OIC_GATT_SERVICE_UUID[] = CA_GATT_SERVICE_UUID; static const char OIC_GATT_CHARACTERISTIC_REQUEST_UUID[] = CA_GATT_REQUEST_CHRC_UUID; @@ -60,8 +64,9 @@ static const jint BOND_BONDED = 12; static const jint BOND_BONDING = 11; static const jint BOND_NONE = 10; -static const jint STATE_CONNECTED = 2; -static const jint STATE_DISCONNECTED = 0; +static const uint16_t STATE_CONNECTED = 3; +static const uint16_t STATE_SERVICE_CONNECTED = 2; +static const uint16_t STATE_DISCONNECTED = 1; /** * get method ID for method Name and class diff --git a/resource/csdk/connectivity/src/bt_le_adapter/arduino/cablenwmonitor.cpp b/resource/csdk/connectivity/src/bt_le_adapter/arduino/cablenwmonitor.cpp index f543bb4bd..1063d3472 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/arduino/cablenwmonitor.cpp +++ b/resource/csdk/connectivity/src/bt_le_adapter/arduino/cablenwmonitor.cpp @@ -63,7 +63,7 @@ void CATerminateLENetworkMonitor() OIC_LOG(DEBUG, TAG, "OUT"); } -CAResult_t CAInitializeLEAdapter(const ca_thread_pool_t threadPool) +CAResult_t CAInitializeLEAdapter() { OIC_LOG(DEBUG, TAG, "IN"); OIC_LOG(DEBUG, TAG, "OUT"); diff --git a/resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c b/resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c index 63705b829..f194d535d 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c +++ b/resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c @@ -73,7 +73,12 @@ typedef enum /** * Callback to provide the status of the network change to CA layer. */ -static CANetworkChangeCallback g_networkCallback = NULL; +static CAAdapterChangeCallback g_networkCallback = NULL; + +/** + * Callback to provide the status of the connection change to CA layer. + */ +static CAConnectionChangeCallback g_connectionCallback = NULL; /** * bleAddress of the local adapter. Value will be initialized to zero, @@ -149,8 +154,10 @@ static CAErrorHandleCallback g_errorHandler = NULL; /** * Register network change notification callback. * - * @param[in] netCallback CANetworkChangeCallback callback which will - * be set for the change in network. + * @param[in] netCallback CAAdapterChangeCallback callback which will + * be set for the change in adapter. + * @param[in] connCallback CAConnectionChangeCallback callback which will + * be set for the change in connection. * * @return 0 on success otherwise a positive error value. * @retval ::CA_STATUS_OK Successful. @@ -158,7 +165,8 @@ static CAErrorHandleCallback g_errorHandler = NULL; * @retval ::CA_STATUS_FAILED Operation failed. * */ -static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback); +static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback, + CAConnectionChangeCallback connCallback); /** * Set the thread pool handle which is required for spawning new @@ -1721,7 +1729,8 @@ static CAResult_t CALEAdapterGattClientStop() CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback, CANetworkPacketReceivedCallback reqRespCallback, - CANetworkChangeCallback netCallback, + CAAdapterChangeCallback netCallback, + CAConnectionChangeCallback connCallback, CAErrorHandleCallback errorCallback, ca_thread_pool_t handle) { @@ -1731,6 +1740,7 @@ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback, VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null"); VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null"); VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null"); + VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null"); CAResult_t result = CA_STATUS_OK; result = CAInitLEAdapterMutex(); @@ -1746,7 +1756,7 @@ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback, OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed"); return CA_STATUS_FAILED; } - CAInitializeLEAdapter(handle); + CAInitializeLEAdapter(); CASetLEClientThreadPoolHandle(handle); @@ -1772,7 +1782,7 @@ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback, CASetBLEClientErrorHandleCallback(CALEErrorHandler); CASetBLEServerErrorHandleCallback(CALEErrorHandler); - CALERegisterNetworkNotifications(netCallback); + CALERegisterNetworkNotifications(netCallback, connCallback); g_errorHandler = errorCallback; @@ -1841,7 +1851,7 @@ static void CATerminateLE() CASetLEReqRespServerCallback(NULL); CASetLEReqRespClientCallback(NULL); - CALERegisterNetworkNotifications(NULL); + CALERegisterNetworkNotifications(NULL, NULL); CASetLEReqRespAdapterCallback(NULL); CATerminateLENetworkMonitor(); @@ -1907,6 +1917,7 @@ static CAResult_t CAStartLEListeningServer() OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled"); + result = CA_STATUS_OK; } } else @@ -1963,6 +1974,7 @@ static CAResult_t CAStartLEDiscoveryServer() OIC_LOG(DEBUG, CALEADAPTER_TAG, "Discovery Server will be started once BT Adapter is enabled"); + result = CA_STATUS_OK; } } else @@ -2157,12 +2169,14 @@ static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *siz return CA_STATUS_OK; } -static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback) +static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback, + CAConnectionChangeCallback connCallback) { OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN"); ca_mutex_lock(g_bleNetworkCbMutex); g_networkCallback = netCallback; + g_connectionCallback = connCallback; ca_mutex_unlock(g_bleNetworkCbMutex); CAResult_t res = CA_STATUS_OK; if (netCallback) @@ -2172,12 +2186,6 @@ static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCa { OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!"); } - - res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb); - if (CA_STATUS_OK != res) - { - OIC_LOG(ERROR, CALEADAPTER_TAG, "CALEConnectionStateChangedCb failed!"); - } } else { @@ -2188,6 +2196,15 @@ static CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCa } } + if (g_connectionCallback) + { + res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb); + if (CA_STATUS_OK != res) + { + OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!"); + } + } + OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT"); return res; } @@ -2250,6 +2267,16 @@ static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const cha #endif } + CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE }; + OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address); + + ca_mutex_lock(g_bleNetworkCbMutex); + if (g_connectionCallback) + { + g_connectionCallback(&localEndpoint, isConnected); + } + ca_mutex_unlock(g_bleNetworkCbMutex); + OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT"); } @@ -2257,15 +2284,6 @@ static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state) { OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEDeviceStateChangedCb"); - VERIFY_NON_NULL_VOID(g_localBLEAddress, CALEADAPTER_TAG, "g_localBLEAddress is null"); - CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE }; - - ca_mutex_lock(g_bleLocalAddressMutex); - OICStrcpy(localEndpoint.addr, - sizeof(localEndpoint.addr), - g_localBLEAddress); - ca_mutex_unlock(g_bleLocalAddressMutex); - if (CA_ADAPTER_ENABLED == adapter_state) { ca_mutex_lock(g_bleIsServerMutex); @@ -2310,7 +2328,7 @@ static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state) ca_mutex_lock(g_bleNetworkCbMutex); if (NULL != g_networkCallback) { - g_networkCallback(&localEndpoint, adapter_state); + g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state); } else { diff --git a/resource/csdk/connectivity/src/bt_le_adapter/linux/caleinterface.c b/resource/csdk/connectivity/src/bt_le_adapter/linux/caleinterface.c index 0b3e94672..57aa4eb0b 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/linux/caleinterface.c +++ b/resource/csdk/connectivity/src/bt_le_adapter/linux/caleinterface.c @@ -772,9 +772,8 @@ static bool CALEWaitForNonEmptyList(GList * const * list, // ----------------------------------------------------------------------- -CAResult_t CAInitializeLEAdapter(const ca_thread_pool_t threadPool) +CAResult_t CAInitializeLEAdapter() { - (void)threadPool; #if !GLIB_CHECK_VERSION(2,36,0) /* Initialize the GLib type system. diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.c index 3d4fd248f..67a44ea7b 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.c +++ b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.c @@ -247,6 +247,9 @@ void CALEGattConnectionStateChanged(bool connected, const char *remoteAddress) if (!connected) { OIC_LOG_V(DEBUG, TAG, "DisConnected from [%s] ", remoteAddress); + ca_mutex_lock(g_LEServerListMutex); + CARemoveLEServerInfoFromList(&g_LEServerList, remoteAddress); + ca_mutex_unlock(g_LEServerListMutex); } else { @@ -373,40 +376,12 @@ CAResult_t CAStartLEGattClient() { OIC_LOG(DEBUG, TAG, "IN"); - ca_mutex_lock(g_LEClientThreadPoolMutex); - if (NULL == g_LEClientThreadPool) - { - OIC_LOG(ERROR, TAG, "gBleServerThreadPool is NULL"); - CATerminateGattClientMutexVariables(); - ca_mutex_unlock(g_LEClientThreadPoolMutex); - return CA_STATUS_FAILED; - } - - CAResult_t result = ca_thread_pool_add_task(g_LEClientThreadPool, CAStartLEGattClientThread, - NULL); - if (CA_STATUS_OK != result) - { - OIC_LOG(ERROR, TAG, "ca_thread_pool_add_task failed"); - CATerminateGattClientMutexVariables(); - ca_mutex_unlock(g_LEClientThreadPoolMutex); - return CA_STATUS_FAILED; - } - ca_mutex_unlock(g_LEClientThreadPoolMutex); - - OIC_LOG(DEBUG, TAG, "OUT"); - return CA_STATUS_OK; -} - -void CAStartLEGattClientThread(void *data) -{ - OIC_LOG(DEBUG, TAG, "IN"); - ca_mutex_lock(g_LEClientStateMutex); if (true == g_isLEGattClientStarted) { OIC_LOG(ERROR, TAG, "Gatt Client is already running!!"); ca_mutex_unlock(g_LEClientStateMutex); - return; + return CA_STATUS_FAILED; } CAResult_t result = CALEGattSetCallbacks(); @@ -415,7 +390,7 @@ void CAStartLEGattClientThread(void *data) OIC_LOG(ERROR, TAG, "CABleGattSetCallbacks Failed"); ca_mutex_unlock(g_LEClientStateMutex); CATerminateLEGattClient(); - return; + return CA_STATUS_FAILED; } g_isLEGattClientStarted = true; @@ -427,7 +402,7 @@ void CAStartLEGattClientThread(void *data) OIC_LOG(ERROR, TAG, "gBleServerThreadPool is NULL"); CATerminateGattClientMutexVariables(); ca_mutex_unlock(g_LEClientThreadPoolMutex); - return; + return CA_STATUS_FAILED; } result = ca_thread_pool_add_task(g_LEClientThreadPool, CAStartTimerThread, @@ -435,22 +410,14 @@ void CAStartLEGattClientThread(void *data) if (CA_STATUS_OK != result) { OIC_LOG(ERROR, TAG, "ca_thread_pool_add_task failed"); + CATerminateGattClientMutexVariables(); ca_mutex_unlock(g_LEClientThreadPoolMutex); - return; + return CA_STATUS_FAILED; } ca_mutex_unlock(g_LEClientThreadPoolMutex); - OIC_LOG(DEBUG, TAG, "Giving the control to threadPool"); - - GMainContext *thread_context = g_main_context_new(); - - g_eventLoop = g_main_loop_new(thread_context, FALSE); - - g_main_context_push_thread_default(thread_context); - - g_main_loop_run(g_eventLoop); - OIC_LOG(DEBUG, TAG, "OUT"); + return CA_STATUS_OK; } void CAStartTimerThread(void *data) @@ -1020,7 +987,7 @@ CAResult_t CALEGattDiscoverServices(const char *remoteAddress) CAResult_t result = CAAddLEServerInfoToList(&g_LEServerList, serverInfo); if (CA_STATUS_OK != result) { - OIC_LOG(ERROR, TAG, "CAAddBLEClientInfoToList failed"); + OIC_LOG(ERROR, TAG, "CAAddLEServerInfoToList failed"); bt_gatt_client_destroy(clientHandle); CALEGattDisConnect(remoteAddress); return CA_STATUS_FAILED; diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.h b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.h index e11072ff2..c55e025b0 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.h +++ b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.h @@ -66,15 +66,6 @@ void CALEGattCharacteristicChangedCb(bt_gatt_h characteristic, void CALEGattCharacteristicWriteCb(int result, bt_gatt_h reqHandle, void *userData); /** - * This is the callback which will be called whenever there is change in gatt connection - * with server(Connected/Disconnected) - * - * @param[in] connected State of connection - * @param[in] remoteAddress Mac address of the remote device in which we made connection. - */ -void CALEGattConnectionStateChanged(bool connected, const char *remoteAddress); - -/** * This is the callback which will be called when LE advertisement is found. * * @param[in] result The result of Scanning @@ -85,15 +76,6 @@ void CALEAdapterScanResultCb(int result, bt_adapter_le_device_scan_result_info_s void *userData); /** - * This thread will be used to initialize the Gatt Client and start device discovery. - * 1. Setting neccessary callbacks for connection, characteristics changed and discovery. - * 2. Start device discovery - * - * @param[in] data Currently it will be NULL(no parameter) - */ -void CAStartLEGattClientThread(void *data); - -/** * This thread will be used to Start the timer for scanning. * * @param[in] data Currently it will be NULL(no parameter) diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/calenwmonitor.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/calenwmonitor.c index 47b1b5f71..bd4dedbb1 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/tizen/calenwmonitor.c +++ b/resource/csdk/connectivity/src/bt_le_adapter/tizen/calenwmonitor.c @@ -23,7 +23,6 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> -#include <glib.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> @@ -44,9 +43,6 @@ */ #define TAG "OIC_CA_LE_MONITOR" -static GMainLoop *g_mainloop = NULL; -static ca_thread_pool_t g_threadPoolHandle = NULL; - /** * Maintains the callback to be notified on device state changed. */ @@ -94,11 +90,6 @@ void CALEAdapterStateChangedCb(int result, bt_adapter_state_e adapter_state, void CALENWConnectionStateChangedCb(int result, bool connected, const char *remoteAddress, void *userData); -void CALEMainLoopThread(void *param) -{ - g_main_loop_run(g_mainloop); -} - CAResult_t CAInitializeLENetworkMonitor() { OIC_LOG(DEBUG, TAG, "IN"); @@ -140,10 +131,9 @@ void CATerminateLENetworkMonitor() OIC_LOG(DEBUG, TAG, "OUT"); } -CAResult_t CAInitializeLEAdapter(const ca_thread_pool_t threadPool) +CAResult_t CAInitializeLEAdapter() { OIC_LOG(DEBUG, TAG, "IN"); - g_threadPoolHandle = threadPool; OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; } @@ -151,31 +141,25 @@ CAResult_t CAInitializeLEAdapter(const ca_thread_pool_t threadPool) CAResult_t CAStartLEAdapter() { OIC_LOG(DEBUG, TAG, "IN"); - g_mainloop = g_main_loop_new(NULL, 0); - if(!g_mainloop) - { - OIC_LOG(ERROR, TAG, "g_main_loop_new failed\n"); - return CA_STATUS_FAILED; - } - - if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, CALEMainLoopThread, (void *) NULL)) - { - OIC_LOG(ERROR, TAG, "Failed to create thread!"); - return CA_STATUS_FAILED; - } int ret = bt_initialize(); - if (0 != ret) + if (BT_ERROR_NONE != ret) { OIC_LOG(ERROR, TAG, "bt_initialize failed"); return CA_STATUS_FAILED; } + bt_adapter_state_e adapterState = BT_ADAPTER_DISABLED; + //Get Bluetooth adapter state + ret = bt_adapter_get_state(&adapterState); - ret = bt_adapter_set_visibility(BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE, 0); - if (0 != ret) + if (BT_ERROR_NONE != ret && BT_ADAPTER_ENABLED == adapterState) { - OIC_LOG(ERROR, TAG, "bt_adapter_set_visibility failed"); - return CA_STATUS_FAILED; + ret = bt_adapter_set_visibility(BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE, 0); + if (BT_ERROR_NONE != ret) + { + OIC_LOG(ERROR, TAG, "bt_adapter_set_visibility failed"); + return CA_STATUS_FAILED; + } } ret = bt_adapter_set_state_changed_cb(CALEAdapterStateChangedCb, NULL); @@ -208,16 +192,12 @@ CAResult_t CAStopLEAdapter() } ret = bt_deinitialize(); - if (0 != ret) + if (BT_ERROR_NONE != ret) { OIC_LOG(ERROR, TAG, "bt_deinitialize failed"); return CA_STATUS_FAILED; } - if (g_mainloop) - { - g_main_loop_quit(g_mainloop); - } return CA_STATUS_OK; } @@ -334,6 +314,14 @@ void CALEAdapterStateChangedCb(int result, bt_adapter_state_e adapter_state, } OIC_LOG(DEBUG, TAG, "Adapter is Enabled"); + + int ret = bt_adapter_set_visibility(BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE, 0); + if (BT_ERROR_NONE != ret) + { + OIC_LOG(ERROR, TAG, "bt_adapter_set_visibility failed"); + return; + } + g_bleDeviceStateChangedCallback(CA_ADAPTER_ENABLED); ca_mutex_unlock(g_bleDeviceStateChangedCbMutex); diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.c index 125de56d5..672e7fb86 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.c +++ b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.c @@ -24,6 +24,7 @@ #include "camutex.h" #include "caqueueingthread.h" #include "cagattservice.h" +#include "oic_string.h" #include "oic_malloc.h" #include "caleutil.h" @@ -114,12 +115,15 @@ static ca_thread_pool_t g_leServerThreadPool = NULL; */ static GMainLoop *g_eventLoop = NULL; -static CALEConnectionStateChangedCallback g_connStateCb = NULL; +/** + * This contains the list of OIC clients connected to the server. + */ +static LEClientInfoList *g_LEClientList = NULL; -void CASetLEConnectionStateChangedCallback(CALEConnectionStateChangedCallback connStateCb) -{ - g_connStateCb = connStateCb; -} +/** + * Mutex to synchronize access to LE ClientList. + */ +static ca_mutex g_LEClientListMutex = NULL; void CALEGattServerConnectionStateChanged(bool connected, const char *remoteAddress) { @@ -128,6 +132,17 @@ void CALEGattServerConnectionStateChanged(bool connected, const char *remoteAddr if (connected) { OIC_LOG_V(DEBUG, TAG, "Connected to [%s]", remoteAddress); + char *addr = OICStrdup(remoteAddress); + ca_mutex_lock(g_LEClientListMutex); + CAResult_t result = CAAddLEClientInfoToList(&g_LEClientList, addr); + if (CA_STATUS_OK != result) + { + OIC_LOG(ERROR, TAG, "CAAddLEClientInfoToList failed"); + ca_mutex_unlock(g_LEClientListMutex); + OICFree(addr); + return; + } + ca_mutex_unlock(g_LEClientListMutex); if (g_connStateCb) { g_connStateCb(CA_ADAPTER_GATT_BTLE, remoteAddress, true); @@ -136,6 +151,9 @@ void CALEGattServerConnectionStateChanged(bool connected, const char *remoteAddr else { OIC_LOG_V(DEBUG, TAG, "Disconnected from [%s]", remoteAddress); + ca_mutex_lock(g_LEClientListMutex); + CARemoveLEClientInfoFromList(&g_LEClientList, remoteAddress); + ca_mutex_unlock(g_LEClientListMutex); if (g_connStateCb) { g_connStateCb(CA_ADAPTER_GATT_BTLE, remoteAddress, false); @@ -153,24 +171,84 @@ CAResult_t CAStartLEGattServer() { OIC_LOG(DEBUG, TAG, "IN"); - ca_mutex_lock(g_leServerThreadPoolMutex); - if (NULL == g_leServerThreadPool) + ca_mutex_lock(g_leServerStateMutex); + if (true == g_isLEGattServerStarted) + { + OIC_LOG(ERROR, TAG, "Gatt Server is already running"); + ca_mutex_unlock(g_leServerStateMutex); + return CA_STATUS_OK; + } + + CAResult_t ret = CAInitLEGattServer(); + if (CA_STATUS_OK != ret) + { + OIC_LOG_V(ERROR, TAG, "CAInitLEGattServer failed[%d]", ret); + ca_mutex_unlock(g_leServerStateMutex); + CATerminateLEGattServer(); + return CA_STATUS_FAILED; + } + + char *serviceUUID = CA_GATT_SERVICE_UUID; + + ret = CAAddNewLEServiceInGattServer(serviceUUID); + if (CA_STATUS_OK != ret) { - OIC_LOG(ERROR, TAG, "g_leServerThreadPool is NULL"); - ca_mutex_unlock(g_leServerThreadPoolMutex); + OIC_LOG_V(ERROR, TAG, "CAAddNewLEServiceInGattServer failed[%d]", ret); + ca_mutex_unlock(g_leServerStateMutex); + CATerminateLEGattServer(); return CA_STATUS_FAILED; } - CAResult_t ret = ca_thread_pool_add_task(g_leServerThreadPool, CAStartLEGattServerThread, - NULL); + static const char charReadUUID[] = CA_GATT_RESPONSE_CHRC_UUID; + char charReadValue[] = {33, 44, 55, 66}; // These are initial random values + + // For Read Characteristics. + ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charReadUUID, charReadValue, + CA_LE_INITIAL_BUF_SIZE, true); if (CA_STATUS_OK != ret) { - OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", ret); - ca_mutex_unlock(g_leServerThreadPoolMutex); + OIC_LOG_V(ERROR, TAG, "CAAddNewCharacteristicsToGattServer failed[%d]", ret); + ca_mutex_unlock(g_leServerStateMutex); + CATerminateLEGattServer(); return CA_STATUS_FAILED; } - ca_mutex_unlock(g_leServerThreadPoolMutex); + static const char charWriteUUID[] = CA_GATT_REQUEST_CHRC_UUID; + char charWriteValue[] = {33, 44, 55, 66}; // These are initial random values + + + ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charWriteUUID, charWriteValue, + CA_LE_INITIAL_BUF_SIZE, false); // For Write Characteristics. + if (CA_STATUS_OK != ret ) + { + OIC_LOG_V(ERROR, TAG, "CAAddNewCharacteristicsToGattServer failed[%d]", ret); + ca_mutex_unlock(g_leServerStateMutex); + CATerminateLEGattServer(); + return CA_STATUS_FAILED; + } + + ret = CARegisterLEServicewithGattServer(g_gattSvcPath); + if (CA_STATUS_OK != ret ) + { + OIC_LOG_V(ERROR, TAG, "CARegisterLEServicewithGattServer failed[%d]", ret); + ca_mutex_unlock(g_leServerStateMutex); + CATerminateLEGattServer(); + return CA_STATUS_FAILED; + } + + ret = CALEStartAdvertise(serviceUUID); + if (CA_STATUS_OK != ret) + { + OIC_LOG_V(ERROR, TAG, "CALEStartAdvertise failed[%d]", ret); + ca_mutex_unlock(g_leServerStateMutex); + CATerminateLEGattServer(); + return CA_STATUS_FAILED; + } + + g_isLEGattServerStarted = true; + + ca_mutex_unlock(g_leServerStateMutex); + OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; } @@ -249,103 +327,6 @@ CAResult_t CALEStopAdvertise() return CA_STATUS_OK; } -void CAStartLEGattServerThread(void *data) -{ - OIC_LOG(DEBUG, TAG, "IN"); - ca_mutex_lock(g_leServerStateMutex); - if (true == g_isLEGattServerStarted) - { - OIC_LOG(ERROR, TAG, "Gatt Server is already running"); - ca_mutex_unlock(g_leServerStateMutex); - CATerminateLEGattServer(); - return; - } - - CAResult_t ret = CAInitLEGattServer(); - if (CA_STATUS_OK != ret) - { - OIC_LOG_V(ERROR, TAG, "CAInitLEGattService failed[%d]", ret); - ca_mutex_unlock(g_leServerStateMutex); - CATerminateLEGattServer(); - return; - } - - char *serviceUUID = CA_GATT_SERVICE_UUID; - - ret = CAAddNewLEServiceInGattServer(serviceUUID); - if (CA_STATUS_OK != ret) - { - OIC_LOG_V(ERROR, TAG, "CAAddNewLEServiceInGattServer failed[%d]", ret); - ca_mutex_unlock(g_leServerStateMutex); - CATerminateLEGattServer(); - return; - } - - static const char charReadUUID[] = CA_GATT_RESPONSE_CHRC_UUID; - char charReadValue[] = {33, 44, 55, 66}; // These are initial random values - - // For Read Characteristics. - ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charReadUUID, charReadValue, - CA_LE_INITIAL_BUF_SIZE, true); - if (CA_STATUS_OK != ret) - { - OIC_LOG_V(ERROR, TAG, "CAAddNewCharacteristicsToGattServer failed[%d]", ret); - ca_mutex_unlock(g_leServerStateMutex); - CATerminateLEGattServer(); - return; - } - - static const char charWriteUUID[] = CA_GATT_REQUEST_CHRC_UUID; - char charWriteValue[] = {33, 44, 55, 66}; // These are initial random values - - - ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charWriteUUID, charWriteValue, - CA_LE_INITIAL_BUF_SIZE, false); // For Write Characteristics. - if (CA_STATUS_OK != ret ) - { - OIC_LOG_V(ERROR, TAG, "CAAddNewCharacteristicsToGattServer failed[%d]", ret); - ca_mutex_unlock(g_leServerStateMutex); - CATerminateLEGattServer(); - return; - } - - ret = CARegisterLEServicewithGattServer(g_gattSvcPath); - if (CA_STATUS_OK != ret ) - { - OIC_LOG_V(ERROR, TAG, "CARegisterLEServicewithGattServer failed[%d]", ret); - ca_mutex_unlock(g_leServerStateMutex); - CATerminateLEGattServer(); - return; - } - - ret = CALEStartAdvertise(serviceUUID); - if (CA_STATUS_OK != ret) - { - OIC_LOG_V(ERROR, TAG, "CALEStartAdvertise failed[%d]", ret); - ca_mutex_unlock(g_leServerStateMutex); - CATerminateLEGattServer(); - return; - } - - g_isLEGattServerStarted = true; - - ca_mutex_unlock(g_leServerStateMutex); - - OIC_LOG(DEBUG, TAG, "LE Server initialization complete."); - - GMainContext *thread_context = NULL; - - thread_context = g_main_context_new(); - - g_eventLoop = g_main_loop_new(thread_context, FALSE); - - g_main_context_push_thread_default(thread_context); - - g_main_loop_run(g_eventLoop); - - OIC_LOG(DEBUG, TAG, "OUT"); -} - CAResult_t CAStopLEGattServer() { OIC_LOG(DEBUG, TAG, "IN"); @@ -361,6 +342,11 @@ CAResult_t CAStopLEGattServer() g_isLEGattServerStarted = false; + ca_mutex_lock(g_LEClientListMutex); + CADisconnectAllClient(g_LEClientList); + g_LEClientList = NULL; + ca_mutex_unlock(g_LEClientListMutex); + CAResult_t res = CALEStopAdvertise(); { OIC_LOG_V(ERROR, TAG, "CALEStopAdvertise failed with ret[%d]", res); @@ -478,6 +464,28 @@ CAResult_t CAInitGattServerMutexVariables() return CA_STATUS_FAILED; } } + + if (NULL == g_leServerThreadPoolMutex) + { + g_leServerThreadPoolMutex = ca_mutex_new(); + if (NULL == g_leServerThreadPoolMutex) + { + OIC_LOG(ERROR, TAG, "ca_mutex_new failed"); + return CA_STATUS_FAILED; + } + } + + if (NULL == g_LEClientListMutex) + { + g_LEClientListMutex = ca_mutex_new(); + if (NULL == g_LEClientListMutex) + { + OIC_LOG(ERROR, TAG, "ca_mutex_new failed"); + return CA_STATUS_FAILED; + } + } + + OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; } @@ -497,6 +505,12 @@ void CATerminateGattServerMutexVariables() ca_mutex_free(g_leReqRespCbMutex); g_leReqRespCbMutex = NULL; + ca_mutex_free(g_leServerThreadPoolMutex); + g_leServerThreadPoolMutex = NULL; + + ca_mutex_free(g_LEClientListMutex); + g_LEClientListMutex = NULL; + OIC_LOG(DEBUG, TAG, "OUT"); } diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.h b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.h index 100ea9b26..400f81f7f 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.h +++ b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.h @@ -41,15 +41,6 @@ #include "caleinterface.h" /** - * This is thread which will be used for creating ble service and advertise ble service. - * 1. Create New OIC Service 2. Add read & write characteristics to service. - * 3. Register Service 4. Advertise service. - * - * @param[in] data Currently it will be NULL. - */ -void CAStartLEGattServerThread(void *data); - -/** * Used to initialize gatt server. * * @return ::CA_STATUS_OK or Appropriate error code. @@ -159,15 +150,6 @@ void CALEGattRemoteCharacteristicWriteCb(char *remoteAddress, bt_gatt_server_h s int charValueLen, void *userData); /** - * This is the callback which will be called whenever there is change in gatt connection - * with Client(Connected/Disconnected). - * - * @param[in] connected State of connection. - * @param[in] remoteAddress Mac address of the remote device in which we made connection. - */ -void CALEGattServerConnectionStateChanged(bool connected, const char *remoteAddress); - -/** * Setting the connection state changed callback. * @param[in] connStateCb callback for receiving the changed network info. */ diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleutil.c b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleutil.c index 8dc46dde1..f77a47b39 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleutil.c +++ b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleutil.c @@ -69,8 +69,8 @@ CAResult_t CAAddLEServerInfoToList(LEServerInfoList **serverList, OIC_LOG(DEBUG, TAG, "IN"); - VERIFY_NON_NULL(serverList, TAG, "clientList"); - VERIFY_NON_NULL(leServerInfo, TAG, "leClientInfo"); + VERIFY_NON_NULL(serverList, TAG, "serverList"); + VERIFY_NON_NULL(leServerInfo, TAG, "leServerInfo"); LEServerInfoList *node = (LEServerInfoList *) OICCalloc(1, sizeof(LEServerInfoList)); if (NULL == node) @@ -102,6 +102,42 @@ CAResult_t CAAddLEServerInfoToList(LEServerInfoList **serverList, return CA_STATUS_OK; } +void CARemoveLEServerInfoFromList(LEServerInfoList **serverList, + const char *remoteAddress) +{ + OIC_LOG(DEBUG, TAG, "IN"); + VERIFY_NON_NULL_VOID(serverList, TAG, "serverList"); + VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remoteAddress"); + + LEServerInfoList *temp = *serverList; + LEServerInfoList *prev = NULL; + while (temp) + { + if (!strcasecmp(temp->serverInfo->remoteAddress, remoteAddress)) + { + if (NULL == prev) + { + *serverList = temp->next; + } + else + { + prev->next = temp->next; + } + CADecrementRegisteredServiceCount(); + bt_gatt_client_destroy(temp->serverInfo->clientHandle); + OICFree(temp->serverInfo->remoteAddress); + OICFree(temp->serverInfo); + OICFree(temp); + OIC_LOG_V(DEBUG, TAG, "Device [%s] removed from list", remoteAddress); + break; + } + prev = temp; + temp = temp->next; + } + + OIC_LOG(DEBUG, TAG, "OUT"); +} + CAResult_t CAGetLEServerInfo(LEServerInfoList *serverList, const char *leAddress, LEServerInfo **leServerInfo) { @@ -162,13 +198,13 @@ CAResult_t CAGetLEServerInfoByPosition(LEServerInfoList *serverList, int32_t pos return CA_STATUS_FAILED; } -void CAFreeLEServerList(LEServerInfoList *clientList) +void CAFreeLEServerList(LEServerInfoList *serverList) { OIC_LOG(DEBUG, TAG, "IN"); - while (clientList) + while (serverList) { - LEServerInfoList *temp = clientList; - clientList = clientList->next; + LEServerInfoList *temp = serverList; + serverList = serverList->next; CAFreeLEServerInfo(temp->serverInfo); OICFree(temp); } @@ -199,6 +235,95 @@ void CAFreeLEServerInfo(LEServerInfo *leServerInfo) OIC_LOG(DEBUG, TAG, "OUT"); } +CAResult_t CAAddLEClientInfoToList(LEClientInfoList **clientList, + char *clientAddress) +{ + OIC_LOG(DEBUG, TAG, "IN"); + VERIFY_NON_NULL(clientList, TAG, "clientList"); + VERIFY_NON_NULL(clientAddress, TAG, "clientAddress"); + + LEClientInfoList *node = (LEClientInfoList *) OICCalloc(1, sizeof(LEClientInfoList)); + if (NULL == node) + { + OIC_LOG(ERROR, TAG, "Malloc failed!"); + return CA_STATUS_FAILED; + } + + node->remoteAddress= clientAddress; + node->next = NULL; + + if (*clientList == NULL) // Empty list + { + *clientList = node; + } + else // Add at front end + { + node->next = *clientList; + *clientList = node; + } + + OIC_LOG_V(DEBUG, TAG, "Device [%s] added to list", clientAddress); + OIC_LOG(DEBUG, TAG, "OUT"); + return CA_STATUS_OK; +} + +void CARemoveLEClientInfoFromList(LEClientInfoList **clientList, + const char *clientAddress) +{ + OIC_LOG(DEBUG, TAG, "IN"); + VERIFY_NON_NULL_VOID(clientAddress, TAG, "clientAddress"); + + LEClientInfoList *temp = *clientList; + LEClientInfoList *prev = NULL; + while (temp) + { + if (!strcasecmp(temp->remoteAddress, clientAddress)) + { + if (NULL == prev) + { + *clientList = temp->next; + } + else + { + prev->next = temp->next; + } + OICFree(temp->remoteAddress); + OICFree(temp); + OIC_LOG_V(DEBUG, TAG, "Device [%s] removed from list", clientAddress); + break; + } + prev = temp; + temp = temp->next; + } + + OIC_LOG(DEBUG, TAG, "OUT"); +} + +void CADisconnectAllClient(LEClientInfoList *clientList) +{ + OIC_LOG(DEBUG, TAG, "IN"); + while (clientList) + { + LEClientInfoList *temp = clientList; + clientList = clientList->next; + if (temp->remoteAddress) + { + int32_t ret = bt_gatt_disconnect(temp->remoteAddress); + + if (BT_ERROR_NONE != ret) + { + OIC_LOG_V(ERROR, TAG, + "bt_gatt_disconnect Failed with ret value [%d]", + ret); + return; + } + OICFree(temp->remoteAddress); + } + OICFree(temp); + } + OIC_LOG(DEBUG, TAG, "OUT"); +} + const char *CALEGetErrorMsg(bt_error_e err) { const char *errStr = NULL; diff --git a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleutil.h b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleutil.h index 5a38ec4e5..ed51602d8 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleutil.h +++ b/resource/csdk/connectivity/src/bt_le_adapter/tizen/caleutil.h @@ -51,6 +51,12 @@ typedef struct _LEServerInfoList struct _LEServerInfoList *next; }LEServerInfoList; +typedef struct _LEClientInfoList +{ + char *remoteAddress; + struct _LEClientInfoList *next; +} LEClientInfoList; + /** * Different characteristics types. * @@ -86,7 +92,7 @@ void CAResetRegisteredServiceCount(); int32_t CAGetRegisteredServiceCount(); /** - * @brief Used to add the serverListInfo structure to the Client List. + * Used to add the serverListInfo structure to the Server List. * * @param[in] serverList Pointer to the ble server list which holds the info of list of * servers registered by the client. @@ -101,6 +107,16 @@ CAResult_t CAAddLEServerInfoToList(LEServerInfoList **serverList, LEServerInfo *leServerInfo); /** + * Used to remove the serverListInfo structure from the Server List. + * + * @param[in,out] serverList Pointer to the ble server list which holds the info of list of + * servers registered by the client. + * @param[in] remoteAddress Remote address to be removed from the client list. + */ +void CARemoveLEServerInfoFromList(LEServerInfoList **serverList, + const char *remoteAddress); + +/** * Used to get the serviceInfo from the list. * * @param[in] serverList Pointer to the ble service list which holds the info of list @@ -147,6 +163,38 @@ void CAFreeLEServerList(LEServerInfoList *serverList); void CAFreeLEServerInfo(LEServerInfo *bleServerInfo); /** + * Used to add the client address to the Client List. + * + * @param[in] clientList Pointer to the ble client list which holds the info of list of + * clients connected to the server. + * @param[in] clientAddress Client remote address. + * @return ::CA_STATUS_OK or Appropriate error code. + * @retval ::CA_STATUS_OK Successful. + * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments. + * @retval ::CA_STATUS_FAILED Operation failed. + */ +CAResult_t CAAddLEClientInfoToList(LEClientInfoList **clientList, + char *clientAddress); + +/** + * Used to remove the client address from the Client List. + * + * @param[in,out] clientList Pointer to the ble client list which holds the info of list of + * clients connected by the server. + * @param[in] clientAddress Remote address to be removed from the client list. + */ +void CARemoveLEClientInfoFromList(LEClientInfoList **clientList, + const char *clientAddress); + +/** + * Used to disconnect all the clients connected to the server. + * + * @param[in,out] clientList Pointer to the ble client list which holds the info of list of + * clients connected by the server. + */ +void CADisconnectAllClient(LEClientInfoList *clientList); + +/** * Used to get the Error message. * @param[in] err Error code(::bt_error_e). * @return Error string corresponding to the BT error code. diff --git a/resource/csdk/connectivity/src/cablockwisetransfer.c b/resource/csdk/connectivity/src/cablockwisetransfer.c index f2140674f..367aa8530 100644 --- a/resource/csdk/connectivity/src/cablockwisetransfer.c +++ b/resource/csdk/connectivity/src/cablockwisetransfer.c @@ -40,6 +40,7 @@ #include "caremotehandler.h" #include "cablockwisetransfer.h" #include "oic_malloc.h" +#include "oic_string.h" #include "camutex.h" #include "logger.h" @@ -344,6 +345,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; @@ -481,23 +492,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: @@ -576,6 +584,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) { @@ -617,9 +640,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; } @@ -780,6 +812,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, @@ -804,39 +874,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) @@ -884,15 +930,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 @@ -977,39 +1016,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) { @@ -2030,11 +2045,21 @@ CAData_t* CACreateNewDataSet(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint // get resource uri information from received response message // to send next request message to remote device - CAResponseInfo_t resInfo = { 0 }; - CAGetResponseInfoFromPDU(pdu, &resInfo, endpoint); + CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(*resInfo)); + if (!resInfo) + { + OIC_LOG(ERROR, TAG, "memory allocation failed"); + OICFree(requestData.token); + return NULL; + } + CAGetResponseInfoFromPDU(pdu, resInfo, endpoint); requestInfo->method = CA_GET; - requestInfo->info.resourceUri = resInfo.info.resourceUri; + requestInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu->hdr, pdu->length); + requestInfo->info.resourceUri = OICStrdup(resInfo->info.resourceUri); + + // after copying the resource uri, destroy response info. + CADestroyResponseInfoInternal(resInfo); } CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t)); @@ -2194,8 +2219,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"); @@ -2322,93 +2346,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) + if (sendData->responseInfo) { - 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 - { - 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 + CABlockData_t *storedData = CAGetBlockDataFromBlockDataList(blockDataID); + if (storedData) { - OIC_LOG(DEBUG, TAG, "Send request"); - if (NULL != currData->blockDataId - && NULL != currData->blockDataId->id - && currData->blockDataId->idLength > 0 - && NULL != sendData->requestInfo->info.token) + OIC_LOG(DEBUG, TAG, "Send response about the received block request."); + if (storedData->sentData) { - if (CABlockidMatches(currData, blockDataID)) - { - OIC_LOG(ERROR, TAG, "already sent"); - continue; - } + OIC_LOG(DEBUG, TAG, "init block number"); + CADestroyDataSet(storedData->sentData); } + storedData->sentData = CACloneCAData(sendData); + *blockData = storedData; + CADestroyBlockID(blockDataID); + return CA_STATUS_OK; } - else if (sendData->responseInfo) // sendData is responseMessage - { - OIC_LOG(DEBUG, TAG, "Send response"); - if (NULL != currData->blockDataId - && NULL != currData->blockDataId->id - && currData->blockDataId->idLength > 0 - && NULL != sendData->responseInfo->info.token) - { - 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; - } - } - } - else - { - OIC_LOG(ERROR, TAG, "no CAInfo data"); - continue; - } + CADestroyBlockID(blockDataID); } - ca_mutex_unlock(g_context.blockDataListMutex); - - CADestroyBlockID(blockDataID); return CA_STATUS_FAILED; } diff --git a/resource/csdk/connectivity/src/caconnectivitymanager.c b/resource/csdk/connectivity/src/caconnectivitymanager.c index 691e2bc05..82919b7fe 100644 --- a/resource/csdk/connectivity/src/caconnectivitymanager.c +++ b/resource/csdk/connectivity/src/caconnectivitymanager.c @@ -553,9 +553,8 @@ CAResult_t CACloseDtlsSession(const CAEndpoint_t *endpoint) #endif /* __WITH_DTLS__ */ #ifdef TCP_ADAPTER -void CARegisterKeepAliveHandler(CAKeepAliveConnectedCallback ConnHandler, - CAKeepAliveDisconnectedCallback DisconnHandler) +void CARegisterKeepAliveHandler(CAKeepAliveConnectionCallback ConnHandler) { - CATCPSetKeepAliveCallbacks(ConnHandler, DisconnHandler); + CATCPSetKeepAliveCallbacks(ConnHandler); } #endif diff --git a/resource/csdk/connectivity/src/cainterfacecontroller.c b/resource/csdk/connectivity/src/cainterfacecontroller.c index a21f5b528..7ae093c75 100644 --- a/resource/csdk/connectivity/src/cainterfacecontroller.c +++ b/resource/csdk/connectivity/src/cainterfacecontroller.c @@ -49,15 +49,15 @@ #define CA_MEMORY_ALLOC_CHECK(arg) {if (arg == NULL) \ {OIC_LOG(ERROR, TAG, "memory error");goto memory_error_exit;} } - - static CAConnectivityHandler_t *g_adapterHandler = NULL; static uint32_t g_numberOfAdapters = 0; static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL; -static CANetworkChangeCallback g_networkChangeCallback = NULL; +static CAAdapterChangeCallback g_adapterChangeCallback = NULL; + +static CAConnectionChangeCallback g_connChangeCallback = NULL; static CAErrorHandleCallback g_errorHandleCallback = NULL; @@ -124,13 +124,24 @@ static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep, } } -static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status) +static void CAAdapterChangedCallback(CATransportAdapter_t adapter, CANetworkStatus_t status) +{ + // Call the callback. + if (g_adapterChangeCallback != NULL) + { + g_adapterChangeCallback(adapter, status); + } + OIC_LOG_V(DEBUG, TAG, "[%d]adapter status is changed to [%d]", adapter, status); +} + +static void CAConnectionChangedCallback(const CAEndpoint_t *info, bool isConnected) { // Call the callback. - if (g_networkChangeCallback != NULL) + if (g_connChangeCallback != NULL) { - g_networkChangeCallback(info, status); + g_connChangeCallback(info, isConnected); } + OIC_LOG_V(DEBUG, TAG, "[%s] connection status is changed to [%d]", info->addr, isConnected); } static void CAAdapterErrorHandleCallback(const CAEndpoint_t *endpoint, @@ -152,32 +163,32 @@ void CAInitializeAdapters(ca_thread_pool_t handle) // Initialize adapters and register callback. #ifdef IP_ADAPTER - CAInitializeIP(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, + CAInitializeIP(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback, CAAdapterErrorHandleCallback, handle); #endif /* IP_ADAPTER */ #ifdef EDR_ADAPTER - CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, - CAAdapterErrorHandleCallback, handle); + CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback, + CAConnectionChangedCallback, CAAdapterErrorHandleCallback, handle); #endif /* EDR_ADAPTER */ #ifdef LE_ADAPTER - CAInitializeLE(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, - CAAdapterErrorHandleCallback, handle); + CAInitializeLE(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback, + CAConnectionChangedCallback, CAAdapterErrorHandleCallback, handle); #endif /* LE_ADAPTER */ #ifdef RA_ADAPTER - CAInitializeRA(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, + CAInitializeRA(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback, handle); #endif /* RA_ADAPTER */ #ifdef TCP_ADAPTER - CAInitializeTCP(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, - CAAdapterErrorHandleCallback, handle); + CAInitializeTCP(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback, + CAConnectionChangedCallback, CAAdapterErrorHandleCallback, handle); #endif /* TCP_ADAPTER */ #ifdef NFC_ADAPTER - CAInitializeNFC(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, + CAInitializeNFC(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback, CAAdapterErrorHandleCallback, handle); #endif /* NFC_ADAPTER */ } @@ -189,11 +200,13 @@ void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback) g_networkPacketReceivedCallback = callback; } -void CASetNetworkChangeCallback(CANetworkChangeCallback callback) +void CASetNetworkMonitorCallbacks(CAAdapterChangeCallback adapterCB, + CAConnectionChangeCallback connCB) { - OIC_LOG(DEBUG, TAG, "Set network handle callback"); + OIC_LOG(DEBUG, TAG, "Set network monitoring callback"); - g_networkChangeCallback = callback; + g_adapterChangeCallback = adapterCB; + g_connChangeCallback = connCB; } void CASetErrorHandleCallback(CAErrorHandleCallback errorCallback) diff --git a/resource/csdk/connectivity/src/camessagehandler.c b/resource/csdk/connectivity/src/camessagehandler.c index e2eb29557..971be54a0 100644 --- a/resource/csdk/connectivity/src/camessagehandler.c +++ b/resource/csdk/connectivity/src/camessagehandler.c @@ -830,17 +830,6 @@ static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep, coap_delete_pdu(pdu); } -static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status) -{ - (void)info; - (void)status; - - if (g_nwMonitorHandler) - { - g_nwMonitorHandler(info, status); - } -} - void CAHandleRequestResponseCallbacks() { #ifdef SINGLE_THREAD @@ -1033,8 +1022,6 @@ void CASetNetworkMonitorCallback(CANetworkMonitorCallback nwMonitorHandler) CAResult_t CAInitializeMessageHandler() { CASetPacketReceivedCallback(CAReceivedPacketCallback); - - CASetNetworkChangeCallback(CANetworkChangedCallback); CASetErrorHandleCallback(CAErrorHandler); #ifndef SINGLE_THREAD diff --git a/resource/csdk/connectivity/src/caprotocolmessage.c b/resource/csdk/connectivity/src/caprotocolmessage.c index 5ef5a879a..a159931a0 100644 --- a/resource/csdk/connectivity/src/caprotocolmessage.c +++ b/resource/csdk/connectivity/src/caprotocolmessage.c @@ -45,7 +45,6 @@ #define TAG "OIC_CA_PRTCL_MSG" -#define CA_BUFSIZE (128) #define CA_PDU_MIN_SIZE (4) #define CA_PORT_BUFFER_SIZE (4) @@ -446,7 +445,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) : @@ -669,7 +668,10 @@ uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter) && COAP_OPTION_BLOCK1 != opt_iter.type && COAP_OPTION_BLOCK2 != opt_iter.type && COAP_OPTION_SIZE1 != opt_iter.type && COAP_OPTION_SIZE2 != opt_iter.type && COAP_OPTION_CONTENT_FORMAT != opt_iter.type - && COAP_OPTION_ACCEPT != opt_iter.type) + && COAP_OPTION_ACCEPT != opt_iter.type + && COAP_OPTION_URI_HOST != opt_iter.type && COAP_OPTION_URI_PORT != opt_iter.type + && COAP_OPTION_ETAG != opt_iter.type && COAP_OPTION_MAXAGE != opt_iter.type + && COAP_OPTION_PROXY_URI != opt_iter.type && COAP_OPTION_PROXY_SCHEME != opt_iter.type) { count++; } @@ -863,7 +865,17 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint, outInfo->acceptFormat = CA_FORMAT_UNSUPPORTED; } OIC_LOG_V(DEBUG, TAG, "option[%d] has an unsupported format [%d]", - opt_iter.type, (uint8_t)buf[0]); + opt_iter.type, (uint8_t)buf[0]); + } + else if (COAP_OPTION_URI_PORT == opt_iter.type || + COAP_OPTION_URI_HOST == opt_iter.type || + COAP_OPTION_ETAG == opt_iter.type || + COAP_OPTION_MAXAGE == opt_iter.type || + COAP_OPTION_PROXY_URI == opt_iter.type || + COAP_OPTION_PROXY_SCHEME== opt_iter.type) + { + OIC_LOG_V(INFO, TAG, "option[%d] has an unsupported format [%d]", + opt_iter.type, (uint8_t)buf[0]); } else { diff --git a/resource/csdk/connectivity/src/caqueueingthread.c b/resource/csdk/connectivity/src/caqueueingthread.c index 754b1c293..9a6c56af7 100644 --- a/resource/csdk/connectivity/src/caqueueingthread.c +++ b/resource/csdk/connectivity/src/caqueueingthread.c @@ -92,28 +92,6 @@ static void CAQueueingThreadBaseRoutine(void *threadValue) OICFree(message); } - // remove all remained list data. - while (u_queue_get_size(thread->dataQueue) > 0) - { - // get data - u_queue_message_t *message = u_queue_get_element(thread->dataQueue); - - // free - if(NULL != message) - { - if (NULL != thread->destroy) - { - thread->destroy(message->msg, message->size); - } - else - { - OICFree(message->msg); - } - - OICFree(message); - } - } - ca_mutex_lock(thread->threadMutex); ca_cond_signal(thread->threadCond); ca_mutex_unlock(thread->threadMutex); @@ -261,6 +239,29 @@ CAResult_t CAQueueingThreadDestroy(CAQueueingThread_t *thread) ca_mutex_free(thread->threadMutex); thread->threadMutex = NULL; ca_cond_free(thread->threadCond); + + // remove all remained list data. + while (u_queue_get_size(thread->dataQueue) > 0) + { + // get data + u_queue_message_t *message = u_queue_get_element(thread->dataQueue); + + // free + if(NULL != message) + { + if (NULL != thread->destroy) + { + thread->destroy(message->msg, message->size); + } + else + { + OICFree(message->msg); + } + + OICFree(message); + } + } + u_queue_delete(thread->dataQueue); return CA_STATUS_OK; diff --git a/resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c b/resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c index 359811070..f6ebf6b5d 100644 --- a/resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c +++ b/resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c @@ -38,6 +38,8 @@ #define TAG "OIC_CA_IP_MONITOR" +static CAIPConnectionStateChangeCallback g_networkChangeCallback; + static CAInterface_t *CANewInterfaceItem(int index, const char *name, int family, uint32_t addr, int flags); @@ -69,6 +71,11 @@ int CAGetPollingInterval(int interval) return interval; } +void CAIPSetNetworkMonitorCallback(CAIPConnectionStateChangeCallback callback) +{ + g_networkChangeCallback = callback; +} + CAInterface_t *CAFindInterfaceChange() { char buf[MAX_INTERFACE_INFO_LENGTH] = { 0 }; @@ -444,9 +451,9 @@ Java_org_iotivity_ca_CaIpInterface_caIpStateEnabled(JNIEnv *env, jclass class) { (void)env; (void)class; - OIC_LOG(DEBUG, TAG, "caIpStateEnabled"); - CAWakeUpForChange(); + OIC_LOG(DEBUG, TAG, "Wifi is in Activated State"); + g_networkChangeCallback(CA_ADAPTER_IP, CA_INTERFACE_UP); } JNIEXPORT void JNICALL @@ -454,13 +461,7 @@ Java_org_iotivity_ca_CaIpInterface_caIpStateDisabled(JNIEnv *env, jclass class) { (void)env; (void)class; - OIC_LOG(DEBUG, TAG, "caIpStateDisabled"); - u_arraylist_t *iflist = CAIPGetInterfaceInformation(0); - if (!iflist) - { - OIC_LOG_V(ERROR, TAG, "get interface info failed"); - return; - } - u_arraylist_destroy(iflist); + OIC_LOG(DEBUG, TAG, "Wifi is in Deactivated State"); + g_networkChangeCallback(CA_ADAPTER_IP, CA_INTERFACE_DOWN); } diff --git a/resource/csdk/connectivity/src/ip_adapter/caipadapter.c b/resource/csdk/connectivity/src/ip_adapter/caipadapter.c index 308ec6dd1..4c4c9fb65 100644 --- a/resource/csdk/connectivity/src/ip_adapter/caipadapter.c +++ b/resource/csdk/connectivity/src/ip_adapter/caipadapter.c @@ -68,7 +68,7 @@ static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL; /** * Network Changed Callback to CA. */ -static CANetworkChangeCallback g_networkChangeCallback = NULL; +static CAAdapterChangeCallback g_networkChangeCallback = NULL; /** * error Callback to CA adapter. @@ -137,10 +137,16 @@ void CAIPDeinitializeQueueHandles() #endif // SINGLE_THREAD -void CAIPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status) +void CAIPConnectionStateCB(CATransportAdapter_t adapter, CANetworkStatus_t status) { - (void)ipAddress; - (void)status; + if (g_networkChangeCallback) + { + g_networkChangeCallback(adapter, status); + } + else + { + OIC_LOG(ERROR, TAG, "g_networkChangeCallback is NULL"); + } } #ifdef __WITH_DTLS__ @@ -215,7 +221,7 @@ static void CAInitializeIPGlobals() CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback, CANetworkPacketReceivedCallback networkPacketCallback, - CANetworkChangeCallback netCallback, + CAAdapterChangeCallback netCallback, CAErrorHandleCallback errorCallback, ca_thread_pool_t handle) { OIC_LOG(DEBUG, TAG, "IN"); @@ -234,6 +240,9 @@ CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback, caglobals.ip.threadpool = handle; CAIPSetPacketReceiveCallback(CAIPPacketReceivedCB); +#ifndef SINGLE_THREAD + CAIPSetConnectionStateChangeCallback(CAIPConnectionStateCB); +#endif #ifdef __WITH_DTLS__ CAAdapterNetDtlsInit(); diff --git a/resource/csdk/connectivity/src/ip_adapter/caipserver.c b/resource/csdk/connectivity/src/ip_adapter/caipserver.c index c49b06413..a84f156b4 100644 --- a/resource/csdk/connectivity/src/ip_adapter/caipserver.c +++ b/resource/csdk/connectivity/src/ip_adapter/caipserver.c @@ -62,19 +62,19 @@ static struct in_addr IPv4MulticastAddress = { 0 }; #define IPv6_DOMAINS 16 -#define IPv6_MULTICAST_INT "ff01::fd" +#define IPv6_MULTICAST_INT "ff01::158" static struct in6_addr IPv6MulticastAddressInt; -#define IPv6_MULTICAST_LNK "ff02::fd" +#define IPv6_MULTICAST_LNK "ff02::158" static struct in6_addr IPv6MulticastAddressLnk; -#define IPv6_MULTICAST_RLM "ff03::fd" +#define IPv6_MULTICAST_RLM "ff03::158" static struct in6_addr IPv6MulticastAddressRlm; -#define IPv6_MULTICAST_ADM "ff04::fd" +#define IPv6_MULTICAST_ADM "ff04::158" static struct in6_addr IPv6MulticastAddressAdm; -#define IPv6_MULTICAST_SIT "ff05::fd" +#define IPv6_MULTICAST_SIT "ff05::158" static struct in6_addr IPv6MulticastAddressSit; -#define IPv6_MULTICAST_ORG "ff08::fd" +#define IPv6_MULTICAST_ORG "ff08::158" static struct in6_addr IPv6MulticastAddressOrg; -#define IPv6_MULTICAST_GLB "ff0e::fd" +#define IPv6_MULTICAST_GLB "ff0e::158" static struct in6_addr IPv6MulticastAddressGlb; static char *ipv6mcnames[IPv6_DOMAINS] = { @@ -168,6 +168,12 @@ void CADeInitializeIPGlobals() close(caglobals.ip.m4s.fd); caglobals.ip.m4s.fd = -1; } + + if (caglobals.ip.netlinkFd != -1) + { + close(caglobals.ip.netlinkFd); + caglobals.ip.netlinkFd = -1; + } } static void CAReceiveHandler(void *data) @@ -244,7 +250,12 @@ static void CASelectReturned(fd_set *readFds, int ret) else ISSET(m4s, readFds, CA_MULTICAST | CA_IPV4 | CA_SECURE) else if (FD_ISSET(caglobals.ip.netlinkFd, readFds)) { - CAHandleNetlink(); + CAInterface_t *ifchanged = CAFindInterfaceChange(); + if (ifchanged) + { + CAProcessNewInterface(ifchanged); + OICFree(ifchanged); + } break; } else if (FD_ISSET(caglobals.ip.shutdownFds[0], readFds)) @@ -255,13 +266,6 @@ static void CASelectReturned(fd_set *readFds, int ret) { continue; } - - CAInterface_t *ifchanged = CAFindInterfaceChange(); - if (ifchanged) - { - CAProcessNewInterface(ifchanged); - OICFree(ifchanged); - } break; } else @@ -830,64 +834,18 @@ static void CAProcessNewInterface(CAInterface_t *ifitem) OIC_LOG(DEBUG, TAG, "ifitem is null"); return; } - - applyMulticastToInterface6(ifitem->index); - struct in_addr inaddr = { .s_addr = ifitem->ipv4addr }; - applyMulticastToInterface4(inaddr); + if (ifitem->family == AF_INET6) + { + applyMulticastToInterface6(ifitem->index); + } + if (ifitem->family == AF_INET) + { + struct in_addr inaddr = { .s_addr = ifitem->ipv4addr }; + applyMulticastToInterface4(inaddr); + } } static void CAHandleNetlink() { -#ifdef __linux__ - char buf[4096]; - struct nlmsghdr *nh; - struct sockaddr_nl sa; - struct iovec iov = { buf, sizeof (buf) }; - struct msghdr msg = { (void *)&sa, sizeof (sa), &iov, 1, NULL, 0, 0 }; - - size_t len = recvmsg(caglobals.ip.netlinkFd, &msg, 0); - - for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len); nh = NLMSG_NEXT(nh, len)) - { - if (nh != NULL && nh->nlmsg_type != RTM_NEWLINK) - { - continue; - } - - struct ifinfomsg *ifi = (struct ifinfomsg *)NLMSG_DATA(nh); - if (!ifi || (ifi->ifi_flags & IFF_LOOPBACK) || !(ifi->ifi_flags & IFF_RUNNING)) - { - continue; - } - - int newIndex = ifi->ifi_index; - - u_arraylist_t *iflist = CAIPGetInterfaceInformation(newIndex); - if (!iflist) - { - OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno)); - return; - } - - uint32_t listLength = u_arraylist_length(iflist); - for (uint32_t i = 0; i < listLength; i++) - { - CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i); - if (!ifitem) - { - continue; - } - - if ((int)ifitem->index != newIndex) - { - continue; - } - - CAProcessNewInterface(ifitem); - break; // we found the one we were looking for - } - u_arraylist_destroy(iflist); - } -#endif // __linux__ } void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback) @@ -900,6 +858,11 @@ void CAIPSetExceptionCallback(CAIPExceptionCallback callback) g_exceptionCallback = callback; } +void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback) +{ + CAIPSetNetworkMonitorCallback(callback); +} + static void sendData(int fd, const CAEndpoint_t *endpoint, const void *data, uint32_t dlen, const char *cast, const char *fam) diff --git a/resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c b/resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c index f1d5211df..a2f2e4f82 100644 --- a/resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c +++ b/resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c @@ -20,15 +20,29 @@ #include "caipinterface.h" +#include <stdio.h> +#include <string.h> +#include <sys/types.h> +#include <sys/socket.h> #include <sys/types.h> +#include <sys/select.h> #include <ifaddrs.h> +#include <unistd.h> +#include <fcntl.h> +#include <arpa/inet.h> +#include <netinet/in.h> #include <net/if.h> -#include <sys/socket.h> #include <netdb.h> -#include <string.h> #include <errno.h> -#include <unistd.h> +#ifdef __linux__ +#include <linux/netlink.h> +#include <linux/rtnetlink.h> +#include <arpa/inet.h> +#include <netinet/in.h> +#endif + +#include "camutex.h" #include "caadapterutils.h" #include "logger.h" #include "oic_malloc.h" @@ -36,13 +50,137 @@ #define TAG "OIC_CA_IP_MONITOR" -CAResult_t CAIPStartNetworkMonitor() +/** + * Mutex for synchronizing access to cached interface and IP address information. + */ +static ca_mutex g_networkMonitorContextMutex = NULL; + +/** + * Used to storing network interface. + */ +static u_arraylist_t *g_netInterfaceList = NULL; + +static CAIPConnectionStateChangeCallback g_networkChangeCallback = NULL; + +static CAResult_t CAIPInitializeNetworkMonitorList(); +static void CAIPDestroyNetworkMonitorList(); +static CAInterface_t *CANewInterfaceItem(int index, const char *name, int family, + uint32_t addr, int flags); + +static CAResult_t CAIPInitializeNetworkMonitorList() +{ + if (!g_networkMonitorContextMutex) + { + g_networkMonitorContextMutex = ca_mutex_new(); + if (!g_networkMonitorContextMutex) + { + OIC_LOG(ERROR, TAG, "ca_mutex_new has failed"); + return CA_STATUS_FAILED; + } + } + + if (!g_netInterfaceList) + { + g_netInterfaceList = u_arraylist_create(); + if (!g_netInterfaceList) + { + OIC_LOG(ERROR, TAG, "u_arraylist_create has failed"); + CAIPDestroyNetworkMonitorList(); + return CA_STATUS_FAILED; + } + } +} + +static void CAIPDestroyNetworkMonitorList() +{ + if (g_netInterfaceList) + { + u_arraylist_destroy(g_netInterfaceList); + g_netInterfaceList = NULL; + } + + if (g_networkMonitorContextMutex) + { + ca_mutex_free(g_networkMonitorContextMutex); + g_networkMonitorContextMutex = NULL; + } +} + +static bool CACmpNetworkList(uint32_t ifiindex) +{ + if (!g_netInterfaceList) + { + OIC_LOG(ERROR, TAG, "g_netInterfaceList is NULL"); + return false; + } + + ca_mutex_lock(g_networkMonitorContextMutex); + + uint32_t list_length = u_arraylist_length(g_netInterfaceList); + for (uint32_t list_index = 0; list_index < list_length; list_index++) + { + CAInterface_t *currItem = (CAInterface_t *) u_arraylist_get(g_netInterfaceList, list_index); + if (currItem->index == ifiindex) + { + ca_mutex_unlock(g_networkMonitorContextMutex); + return true; + } + } + ca_mutex_unlock(g_networkMonitorContextMutex); + return false; +} + +static CAResult_t CAAddNetworkMonitorList(CAInterface_t *ifitem) { + VERIFY_NON_NULL(g_netInterfaceList, TAG, "g_netInterfaceList is NULL"); + VERIFY_NON_NULL(ifitem, TAG, "ifitem is NULL"); + + ca_mutex_lock(g_networkMonitorContextMutex); + bool result = u_arraylist_add(g_netInterfaceList, (void *) ifitem); + if (!result) + { + OIC_LOG(ERROR, TAG, "u_arraylist_add failed."); + ca_mutex_unlock(g_networkMonitorContextMutex); + return CA_STATUS_FAILED; + } + ca_mutex_unlock(g_networkMonitorContextMutex); return CA_STATUS_OK; } +static void CARemoveNetworkMonitorList(int ifiindex) +{ + VERIFY_NON_NULL_VOID(g_netInterfaceList, TAG, "g_netInterfaceList is NULL"); + + ca_mutex_lock(g_networkMonitorContextMutex); + + uint32_t list_length = u_arraylist_length(g_netInterfaceList); + for (uint32_t list_index = 0; list_index < list_length; list_index++) + { + CAInterface_t *removedifitem = (CAInterface_t *) u_arraylist_get( + g_netInterfaceList, list_index); + if (removedifitem && removedifitem->index == ifiindex) + { + if (u_arraylist_remove(g_netInterfaceList, list_index)) + { + OICFree(removedifitem); + ca_mutex_unlock(g_networkMonitorContextMutex); + return; + } + continue; + } + } + ca_mutex_unlock(g_networkMonitorContextMutex); + return; +} + +CAResult_t CAIPStartNetworkMonitor() +{ + return CAIPInitializeNetworkMonitorList(); +} + CAResult_t CAIPStopNetworkMonitor() { + CAIPDestroyNetworkMonitorList(); return CA_STATUS_OK; } @@ -51,9 +189,96 @@ int CAGetPollingInterval(int interval) return interval; } +void CAIPSetNetworkMonitorCallback(CAIPConnectionStateChangeCallback callback) +{ + g_networkChangeCallback = callback; +} + +static CAInterface_t *CANewInterfaceItem(int index, const char *name, int family, + uint32_t addr, int flags) +{ + CAInterface_t *ifitem = (CAInterface_t *)OICCalloc(1, sizeof (CAInterface_t)); + if (!ifitem) + { + OIC_LOG(ERROR, TAG, "Malloc failed"); + return NULL; + } + + OICStrcpy(ifitem->name, sizeof (ifitem->name), name); + ifitem->index = index; + ifitem->family = family; + ifitem->ipv4addr = addr; + ifitem->flags = flags; + + return ifitem; +} + CAInterface_t *CAFindInterfaceChange() { - return NULL; + CAInterface_t *foundNewInterface = NULL; +#ifdef __linux__ + char buf[4096]; + struct nlmsghdr *nh; + struct sockaddr_nl sa; + struct iovec iov = { buf, sizeof (buf) }; + struct msghdr msg = { (void *)&sa, sizeof (sa), &iov, 1, NULL, 0, 0 }; + + size_t len = recvmsg(caglobals.ip.netlinkFd, &msg, 0); + + for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len); nh = NLMSG_NEXT(nh, len)) + { + if (nh != NULL && nh->nlmsg_type != RTM_NEWLINK) + { + continue; + } + + struct ifinfomsg *ifi = (struct ifinfomsg *)NLMSG_DATA(nh); + + int ifiIndex = ifi->ifi_index; + u_arraylist_t *iflist = CAIPGetInterfaceInformation(ifiIndex); + + if ((!ifi || (ifi->ifi_flags & IFF_LOOPBACK) || !(ifi->ifi_flags & IFF_RUNNING))) + { + bool isFound = CACmpNetworkList(ifiIndex); + if (isFound) + { + CARemoveNetworkMonitorList(ifiIndex); + if (g_networkChangeCallback) + { + g_networkChangeCallback(CA_ADAPTER_IP ,CA_INTERFACE_DOWN); + } + } + continue; + } + + if (!iflist) + { + OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno)); + return NULL; + } + + uint32_t listLength = u_arraylist_length(iflist); + for (uint32_t i = 0; i < listLength; i++) + { + CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i); + if (!ifitem) + { + continue; + } + + if ((int)ifitem->index != ifiIndex) + { + continue; + } + + foundNewInterface = CANewInterfaceItem(ifitem->index, ifitem->name, ifitem->family, + ifitem->ipv4addr, ifitem->flags); + break; // we found the one we were looking for + } + u_arraylist_destroy(iflist); + } +#endif + return foundNewInterface; } u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex) @@ -138,9 +363,24 @@ u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex) goto exit; } - OIC_LOG_V(DEBUG, TAG, "Added interface: %s (%d)", ifitem->name, family); + bool isFound = CACmpNetworkList(ifitem->index); + if (!isFound) + { + CAInterface_t *newifitem = CANewInterfaceItem(ifitem->index, ifitem->name, ifitem->family, + ifitem->ipv4addr, ifitem->flags); + CAResult_t ret = CAAddNetworkMonitorList(newifitem); + if (CA_STATUS_OK != ret) + { + OICFree(newifitem); + goto exit; + } + if (g_networkChangeCallback) + { + g_networkChangeCallback(CA_ADAPTER_IP, CA_INTERFACE_UP); + } + OIC_LOG_V(DEBUG, TAG, "Added interface: %s (%d)", ifitem->name, ifitem->family); + } } - freeifaddrs(ifp); return iflist; diff --git a/resource/csdk/connectivity/src/ip_adapter/tizen/caipnwmonitor.c b/resource/csdk/connectivity/src/ip_adapter/tizen/caipnwmonitor.c index 437e53544..0d30c79c8 100644 --- a/resource/csdk/connectivity/src/ip_adapter/tizen/caipnwmonitor.c +++ b/resource/csdk/connectivity/src/ip_adapter/tizen/caipnwmonitor.c @@ -30,6 +30,10 @@ #include <unistd.h> #include <sys/ioctl.h> #include <wifi.h> +#include <linux/netlink.h> +#include <linux/rtnetlink.h> +#include <arpa/inet.h> +#include <netinet/in.h> #include "caadapterutils.h" #include "logger.h" @@ -37,8 +41,13 @@ #include "oic_string.h" #define TAG "IP_MONITOR" + #define MAX_INTERFACE_INFO_LENGTH (1024) +#define NETLINK_MESSAGE_LENGTH (4096) + +static CAIPConnectionStateChangeCallback g_networkChangeCallback; + static CAInterface_t *CANewInterfaceItem(int index, char *name, int family, uint32_t addr, int flags); @@ -56,101 +65,69 @@ int CAGetPollingInterval(int interval) return interval; } -CAInterface_t *CAFindInterfaceChange() +void CAIPSetNetworkMonitorCallback(CAIPConnectionStateChangeCallback callback) { - char buf[MAX_INTERFACE_INFO_LENGTH] = { 0 }; - struct ifconf ifc = { .ifc_len = MAX_INTERFACE_INFO_LENGTH, .ifc_buf = buf }; - - int s = caglobals.ip.u6.fd != -1 ? caglobals.ip.u6.fd : caglobals.ip.u4.fd; - if (ioctl(s, SIOCGIFCONF, &ifc) < 0) - { - OIC_LOG_V(ERROR, TAG, "SIOCGIFCONF failed: %s", strerror(errno)); - return NULL; - } + g_networkChangeCallback = callback; +} +CAInterface_t *CAFindInterfaceChange() +{ CAInterface_t *foundNewInterface = NULL; - - struct ifreq* ifr = ifc.ifc_req; - size_t interfaces = ifc.ifc_len / sizeof (ifc.ifc_req[0]); - size_t ifreqsize = ifc.ifc_len; - - CAIfItem_t *previous = (CAIfItem_t *)OICMalloc(ifreqsize); - if (!previous) + char buf[NETLINK_MESSAGE_LENGTH] = { 0 }; + struct sockaddr_nl sa = { 0 }; + struct iovec iov = { .iov_base = buf, + .iov_len = sizeof (buf) }; + struct msghdr msg = { .msg_name = (void *)&sa, + .msg_namelen = sizeof (sa), + .msg_iov = &iov, + .msg_iovlen = 1 }; + + size_t len = recvmsg(caglobals.ip.netlinkFd, &msg, 0); + + for (struct nlmsghdr *nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len); nh = NLMSG_NEXT(nh, len)) { - OIC_LOG(ERROR, TAG, "OICMalloc failed"); - return NULL; - } - - memcpy(previous, caglobals.ip.nm.ifItems, ifreqsize); - size_t numprevious = caglobals.ip.nm.numIfItems; - - if (ifreqsize > caglobals.ip.nm.sizeIfItems) - { - - CAIfItem_t *items = (CAIfItem_t *)OICRealloc(caglobals.ip.nm.ifItems, ifreqsize); - if (!items) + if (nh != NULL && nh->nlmsg_type != RTM_NEWLINK) { - OIC_LOG(ERROR, TAG, "OICRealloc failed"); - OICFree(previous); - return NULL; + continue; } - caglobals.ip.nm.ifItems = items; - caglobals.ip.nm.sizeIfItems = ifreqsize; - } - caglobals.ip.nm.numIfItems = 0; - for (size_t i = 0; i < interfaces; i++) - { - struct ifreq* item = &ifr[i]; - char *name = item->ifr_name; - struct sockaddr_in *sa4 = (struct sockaddr_in *)&item->ifr_addr; - uint32_t ipv4addr = sa4->sin_addr.s_addr; + struct ifinfomsg *ifi = (struct ifinfomsg *)NLMSG_DATA(nh); - if (ioctl(s, SIOCGIFFLAGS, item) < 0) - { - OIC_LOG_V(ERROR, TAG, "SIOCGIFFLAGS failed: %s", strerror(errno)); - continue; - } - int16_t flags = item->ifr_flags; - if ((flags & IFF_LOOPBACK) || !(flags & IFF_RUNNING)) - { - continue; - } - if (ioctl(s, SIOCGIFINDEX, item) < 0) + int ifiIndex = ifi->ifi_index; + u_arraylist_t *iflist = CAIPGetInterfaceInformation(ifiIndex); + + if ((!ifi || (ifi->ifi_flags & IFF_LOOPBACK) || !(ifi->ifi_flags & IFF_RUNNING))) { - OIC_LOG_V(ERROR, TAG, "SIOCGIFINDEX failed: %s", strerror(errno)); continue; } - int ifIndex = item->ifr_ifindex; - caglobals.ip.nm.ifItems[i].ifIndex = ifIndex; // refill interface list - caglobals.ip.nm.numIfItems++; - - if (foundNewInterface) + if (!iflist) { - continue; // continue updating interface list + OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno)); + return NULL; } - // see if this interface didn't previously exist - bool found = false; - for (size_t j = 0; j < numprevious; j++) + uint32_t listLength = u_arraylist_length(iflist); + for (uint32_t i = 0; i < listLength; i++) { - if (ifIndex == previous[j].ifIndex) + CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i); + if (!ifitem) { - found = true; - break; + continue; + } + + if ((int)ifitem->index != ifiIndex) + { + continue; } - } - if (found) - { - OIC_LOG_V(INFO, TAG, "Interface found: %s", name); - continue; - } - foundNewInterface = CANewInterfaceItem(ifIndex, name, AF_INET, ipv4addr, flags); - } - OICFree(previous); + foundNewInterface = CANewInterfaceItem(ifitem->index, ifitem->name, ifitem->family, + ifitem->ipv4addr, ifitem->flags); + break; // we found the one we were looking for + } + u_arraylist_destroy(iflist); + } return foundNewInterface; } @@ -357,17 +334,11 @@ void CAWIFIConnectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap, if (WIFI_CONNECTION_STATE_CONNECTED == state) { - CAWakeUpForChange(); + g_networkChangeCallback(CA_ADAPTER_IP, CA_INTERFACE_UP); } else { - u_arraylist_t *iflist = CAIPGetInterfaceInformation(0); - if (!iflist) - { - OIC_LOG_V(ERROR, TAG, "get interface info failed"); - return; - } - u_arraylist_destroy(iflist); + g_networkChangeCallback(CA_ADAPTER_IP, CA_INTERFACE_DOWN); } OIC_LOG(DEBUG, TAG, "OUT"); diff --git a/resource/csdk/connectivity/src/nfc_adapter/canfcadapter.c b/resource/csdk/connectivity/src/nfc_adapter/canfcadapter.c index cc34caaaf..eddee4d80 100644 --- a/resource/csdk/connectivity/src/nfc_adapter/canfcadapter.c +++ b/resource/csdk/connectivity/src/nfc_adapter/canfcadapter.c @@ -58,9 +58,9 @@ static CAQueueingThread_t *g_sendQueueHandle = NULL; static CANetworkPacketReceivedCallback g_packetReceivedCallback = NULL; /** - * Network Changed Callback to CA + * Adapter Changed Callback to CA */ -static CANetworkChangeCallback g_connectionStateCallback = NULL; +static CAAdapterChangeCallback g_adapterStateCallback = NULL; /** * error Callback to CA adapter @@ -177,16 +177,16 @@ void CANFCErrorHandler(const CAEndpoint_t *endpoint, const void *data, uint32_t CAResult_t CAInitializeNFC(CARegisterConnectivityCallback registerCallback, CANetworkPacketReceivedCallback packetReceivedCallback, - CANetworkChangeCallback connectionStateCallback, + CAAdapterChangeCallback netCallback, CAErrorHandleCallback errorCallback, ca_thread_pool_t handle) { OIC_LOG(DEBUG, TAG, "IN"); VERIFY_NON_NULL(registerCallback, TAG, "registerCallback"); VERIFY_NON_NULL(packetReceivedCallback, TAG, "packetReceivedCallback"); - VERIFY_NON_NULL(connectionStateCallback, TAG, "connectionStateCallback"); + VERIFY_NON_NULL(netCallback, TAG, "netCallback"); VERIFY_NON_NULL(handle, TAG, "thread pool handle"); - g_connectionStateCallback = connectionStateCallback; + g_adapterStateCallback = netCallback; g_packetReceivedCallback = packetReceivedCallback; g_errorCallback = errorCallback; diff --git a/resource/csdk/connectivity/src/ra_adapter/caraadapter.c b/resource/csdk/connectivity/src/ra_adapter/caraadapter.c index b34cb83aa..fba4ca887 100644 --- a/resource/csdk/connectivity/src/ra_adapter/caraadapter.c +++ b/resource/csdk/connectivity/src/ra_adapter/caraadapter.c @@ -59,7 +59,7 @@ static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL; /** * Network Changed Callback to CA. */ -static CANetworkChangeCallback g_networkChangeCallback = NULL; +static CAAdapterChangeCallback g_networkChangeCallback = NULL; /** * Holds XMPP data information. @@ -91,26 +91,16 @@ void CARANotifyNetworkChange(const char *address, CANetworkStatus_t status) g_xmppData.connectionStatus = status; - CAEndpoint_t *localEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS, - CA_ADAPTER_REMOTE_ACCESS, - address, 0); - if (!localEndpoint) - { - OIC_LOG(ERROR, RA_ADAPTER_TAG, "localEndpoint creation failed!"); - return; - } - CANetworkChangeCallback networkChangeCallback = g_networkChangeCallback; + CAAdapterChangeCallback networkChangeCallback = g_networkChangeCallback; if (networkChangeCallback) { - networkChangeCallback(localEndpoint, status); + networkChangeCallback(CA_ADAPTER_REMOTE_ACCESS, status); } else { OIC_LOG(ERROR, RA_ADAPTER_TAG, "g_networkChangeCallback is NULL"); } - CAFreeEndpoint(localEndpoint); - OIC_LOG(DEBUG, RA_ADAPTER_TAG, "CARANotifyNetworkChange OUT"); } @@ -359,8 +349,8 @@ static int CARAConnHandler(xmpp_t *xmpp, xmppconn_info_t *conninfo, void *udata) } CAResult_t CAInitializeRA(CARegisterConnectivityCallback registerCallback, - CANetworkPacketReceivedCallback networkPacketCallback, - CANetworkChangeCallback netCallback, ca_thread_pool_t handle) + CANetworkPacketReceivedCallback networkPacketCallback, + CAAdapterChangeCallback netCallback, ca_thread_pool_t handle) { OIC_LOG(DEBUG, RA_ADAPTER_TAG, "CAInitializeRA IN"); if (!registerCallback || !networkPacketCallback || !netCallback || !handle) @@ -615,7 +605,7 @@ static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL; /** * Network Changed Callback to CA. */ -static CANetworkChangeCallback g_networkChangeCallback = NULL; +static CAAdapterChangeCallback g_networkChangeCallback = NULL; /** * Holds XMPP data information. @@ -657,26 +647,16 @@ void CARANotifyNetworkChange(const char *address, CANetworkStatus_t status) { OIC_LOG(DEBUG, RA_ADAPTER_TAG, "CARANotifyNetworkChange IN"); - CAEndpoint_t *localEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS, - CA_ADAPTER_REMOTE_ACCESS, - address, 0); - if (!localEndpoint) - { - OIC_LOG(ERROR, RA_ADAPTER_TAG, "localEndpoint creation failed!"); - return; - } - CANetworkChangeCallback networkChangeCallback = g_networkChangeCallback; + CAAdapterChangeCallback networkChangeCallback = g_networkChangeCallback; if (networkChangeCallback) { - networkChangeCallback(localEndpoint, status); + networkChangeCallback(CA_ADAPTER_REMOTE_ACCESS, status); } else { OIC_LOG(ERROR, RA_ADAPTER_TAG, "g_networkChangeCallback is NULL"); } - CAFreeEndpoint(localEndpoint); - OIC_LOG(DEBUG, RA_ADAPTER_TAG, "CARANotifyNetworkChange OUT"); } @@ -783,8 +763,8 @@ void CARAXmppMessageReceivedCB(void * const param, xmpp_error_code_t result, } CAResult_t CAInitializeRA(CARegisterConnectivityCallback registerCallback, - CANetworkPacketReceivedCallback networkPacketCallback, - CANetworkChangeCallback netCallback, ca_thread_pool_t handle) + CANetworkPacketReceivedCallback networkPacketCallback, + CAAdapterChangeCallback netCallback, ca_thread_pool_t handle) { OIC_LOG(DEBUG, RA_ADAPTER_TAG, "CAInitializeRA IN"); if (!registerCallback || !networkPacketCallback || !netCallback || !handle) diff --git a/resource/csdk/connectivity/src/tcp_adapter/catcpadapter.c b/resource/csdk/connectivity/src/tcp_adapter/catcpadapter.c index 110887738..6551c94e5 100644 --- a/resource/csdk/connectivity/src/tcp_adapter/catcpadapter.c +++ b/resource/csdk/connectivity/src/tcp_adapter/catcpadapter.c @@ -71,9 +71,14 @@ static CAQueueingThread_t *g_sendQueueHandle = NULL; static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL; /** - * Network Changed Callback to CA. + * Adapter Changed Callback to CA. */ -static CANetworkChangeCallback g_networkChangeCallback = NULL; +static CAAdapterChangeCallback g_networkChangeCallback = NULL; + +/** + * Connection Changed Callback to CA. + */ +static CAConnectionChangeCallback g_connectionChangeCallback = NULL; /** * error Callback to CA adapter. @@ -84,14 +89,9 @@ static void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data, uint32_t dataLength); /** - * KeepAlive Connected Callback to CA adapter. - */ -static CAKeepAliveConnectedCallback g_connCallback = NULL; - -/** - * KeepAlive Disconnected Callback to CA adapter. + * KeepAlive Connected or Disconnected Callback to CA adapter. */ -static CAKeepAliveDisconnectedCallback g_disconnCallback = NULL; +static CAKeepAliveConnectionCallback g_connKeepAliveCallback = NULL; static CAResult_t CATCPInitializeQueueHandles(); @@ -175,33 +175,32 @@ void CATCPErrorHandler(const CAEndpoint_t *endpoint, const void *data, } } -static void CATCPKeepAliveHandler(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); - - if (isConnected) + // Pass the changed connection status to RI Layer for keepalive. + if (g_connKeepAliveCallback) { - g_connCallback(&endpoint); + g_connKeepAliveCallback(endpoint, isConnected); } - else + + // Pass the changed connection status to CAUtil. + if (g_connectionChangeCallback) { - g_disconnCallback(&endpoint); + g_connectionChangeCallback(endpoint, isConnected); } } -void CATCPSetKeepAliveCallbacks(CAKeepAliveConnectedCallback ConnHandler, - CAKeepAliveDisconnectedCallback DisconnHandler) +void CATCPSetKeepAliveCallbacks(CAKeepAliveConnectionCallback ConnHandler) { - g_connCallback = ConnHandler; - g_disconnCallback = DisconnHandler; - - CATCPSetKeepAliveCallback(CATCPKeepAliveHandler); + g_connKeepAliveCallback = 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; @@ -217,11 +216,13 @@ static void CAInitializeTCPGlobals() } caglobals.tcp.ipv4tcpenabled = flags & CA_IPV4; + caglobals.tcp.ipv6tcpenabled = flags & CA_IPV6; } CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback, CANetworkPacketReceivedCallback networkPacketCallback, - CANetworkChangeCallback netCallback, + CAAdapterChangeCallback netCallback, + CAConnectionChangeCallback connCallback, CAErrorHandleCallback errorCallback, ca_thread_pool_t handle) { OIC_LOG(DEBUG, TAG, "IN"); @@ -231,12 +232,14 @@ CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback, VERIFY_NON_NULL(handle, TAG, "thread pool handle"); g_networkChangeCallback = netCallback; + g_connectionChangeCallback = connCallback; g_networkPacketCallback = networkPacketCallback; g_errorCallback = errorCallback; CAInitializeTCPGlobals(); caglobals.tcp.threadpool = handle; + CATCPSetConnectionChangedCallback(CATCPConnectionHandler); CATCPSetPacketReceiveCallback(CATCPPacketReceivedCB); CATCPSetErrorHandler(CATCPErrorHandler); diff --git a/resource/csdk/connectivity/src/tcp_adapter/catcpserver.c b/resource/csdk/connectivity/src/tcp_adapter/catcpserver.c index 5334502e8..ad8d9e494 100644 --- a/resource/csdk/connectivity/src/tcp_adapter/catcpserver.c +++ b/resource/csdk/connectivity/src/tcp_adapter/catcpserver.c @@ -20,17 +20,16 @@ #include <sys/types.h> #include <sys/socket.h> +#include <sys/select.h> #include <sys/ioctl.h> +#include <sys/poll.h> #include <stdio.h> #include <unistd.h> -#include <sys/types.h> #include <fcntl.h> -#include <sys/select.h> #include <arpa/inet.h> #include <netinet/in.h> #include <net/if.h> #include <errno.h> -#include <sys/poll.h> #ifndef WITH_ARDUINO #include <sys/socket.h> @@ -62,11 +61,6 @@ #define TCP_MAX_HEADER_LEN 6 /** - * Accept server file descriptor. - */ -static int g_acceptServerFD = -1; - -/** * Mutex to synchronize device object list. */ static ca_mutex g_mutexObjectList = NULL; @@ -89,14 +83,14 @@ static CATCPErrorHandleCallback g_TCPErrorHandler = NULL; /** * Connected Callback to pass the connection information to RI. */ -static CATCPKeepAliveHandleCallback g_keepaliveCallback = NULL; +static CATCPConnectionHandleCallback g_connectionCallback = NULL; static CAResult_t CATCPCreateMutex(); static void CATCPDestroyMutex(); static CAResult_t CATCPCreateCond(); static void CATCPDestroyCond(); -static CAResult_t CACreateAcceptSocket(); -static void CAAcceptConnection(); +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 CAReceiveMessage(int fd); @@ -178,9 +172,13 @@ static void CAFindReadyMessage() FD_ZERO(&readFds); - if (-1 != g_acceptServerFD) + if (-1 != caglobals.tcp.ipv4.fd) + { + FD_SET(caglobals.tcp.ipv4.fd, &readFds); + } + if (-1 != caglobals.tcp.ipv6.fd) { - FD_SET(g_acceptServerFD, &readFds); + FD_SET(caglobals.tcp.ipv6.fd, &readFds); } if (-1 != caglobals.tcp.shutdownFds[0]) { @@ -223,11 +221,16 @@ static void CAFindReadyMessage() static void CASelectReturned(fd_set *readFds, int ret) { - (void)ret; + VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL"); - if (g_acceptServerFD != -1 && FD_ISSET(g_acceptServerFD, readFds)) + if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds)) + { + CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4); + return; + } + else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds)) { - CAAcceptConnection(); + CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6); return; } else if (-1 != caglobals.tcp.connectionFds[0] && @@ -264,13 +267,14 @@ static void CASelectReturned(fd_set *readFds, int ret) } } -static void CAAcceptConnection() +static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock) { + VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL"); + struct sockaddr_storage clientaddr; socklen_t clientlen = sizeof (struct sockaddr_in); - int sockfd = accept(g_acceptServerFD, (struct sockaddr *)&clientaddr, - &clientlen); + int sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen); if (-1 != sockfd) { CATCPSessionInfo_t *svritem = @@ -283,6 +287,7 @@ static void CAAcceptConnection() } svritem->fd = sockfd; + svritem->sep.endpoint.flags = flag; CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen, (char *) &svritem->sep.endpoint.addr, &svritem->sep.endpoint.port); @@ -397,94 +402,171 @@ static void CAWakeUpForReadFdsUpdate(const char *host) } } +static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port, + struct sockaddr_storage *sockaddr) +{ + struct addrinfo *addrs = NULL; + struct addrinfo hints = { .ai_family = family, + .ai_protocol = IPPROTO_TCP, + .ai_socktype = SOCK_STREAM, + .ai_flags = AI_NUMERICHOST }; + + int r = getaddrinfo(host, NULL, &hints, &addrs); + if (r) + { + if (EAI_SYSTEM == r) + { + OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno)); + } + else + { + OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r)); + } + freeaddrinfo(addrs); + return CA_STATUS_FAILED; + } + // assumption: in this case, getaddrinfo will only return one addrinfo + // or first is the one we want. + if (addrs[0].ai_family == AF_INET6) + { + memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6)); + ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port); + } + else + { + memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in)); + ((struct sockaddr_in *)sockaddr)->sin_port = htons(port); + } + freeaddrinfo(addrs); + return CA_STATUS_OK; +} + static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem) { - // create tcp socket + // #1. create tcp socket. int fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (-1 == fd) { OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno)); - goto exit; + return -1; } + // #2. convert address from string to binary. struct sockaddr_storage sa = { .ss_family = family }; - CAConvertNameToAddr(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, &sa); - socklen_t socklen = sizeof (struct sockaddr_in); + CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr, + svritem->sep.endpoint.port, &sa); + if (CA_STATUS_OK != res) + { + close(fd); + return -1; + } - // connect to TCP server - int ret = connect(fd, (struct sockaddr *)&sa, socklen); - if (0 == ret) + // #3. set socket length. + socklen_t socklen; + if (sa.ss_family == AF_INET6) { - OIC_LOG(DEBUG, TAG, "connect socket success"); - CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr); + struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa; + if (!sock6->sin6_scope_id) + { + sock6->sin6_scope_id = svritem->sep.endpoint.interface; + } + socklen = sizeof(struct sockaddr_in6); } else { - OIC_LOG(ERROR, TAG, "failed to connect socket"); - goto exit; + socklen = sizeof(struct sockaddr_in); } - return fd; - -exit: - if (fd >= 0) + // #4. connect to remote server device. + if (connect(fd, (struct sockaddr *)&sa, socklen) < 0) { + OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno)); close(fd); + return -1; } - return -1; + + OIC_LOG(DEBUG, TAG, "connect socket success"); + CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr); + return fd; } -static CAResult_t CACreateAcceptSocket() +static int CACreateAcceptSocket(int family, CASocket_t *sock) { - if (g_acceptServerFD != -1) + VERIFY_NON_NULL_RET(sock, TAG, "sock", -1); + + if (sock->fd != -1) { OIC_LOG(DEBUG, TAG, "accept socket created already"); - return CA_STATUS_OK; + return sock->fd; } - int reuse = 1; - struct sockaddr_in server = { .sin_addr.s_addr = INADDR_ANY, - .sin_family = AF_INET, - .sin_port = htons(SERVER_PORT), - .sin_zero = { 0 } }; + socklen_t socklen; + struct sockaddr_storage server = { .ss_family = family }; - g_acceptServerFD = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (g_acceptServerFD < 0) + int fd = socket(family, SOCK_STREAM, IPPROTO_TCP); + if (fd < 0) { OIC_LOG(ERROR, TAG, "Failed to create socket"); goto exit; } - if (-1 == setsockopt(g_acceptServerFD, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))) + if (family == AF_INET6) + { + // the socket is reâ€stricted to sending and receiving IPv6 packets only. + int on = 1; + if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on))) + { + OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno)); + goto exit; + } + ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port); + socklen = sizeof (struct sockaddr_in6); + } + else + { + ((struct sockaddr_in *)&server)->sin_port = htons(sock->port); + socklen = sizeof (struct sockaddr_in); + } + + int reuse = 1; + if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))) { OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR"); goto exit; } - int serverlen = sizeof(server); - if (-1 == bind(g_acceptServerFD, (struct sockaddr *)&server, serverlen)) + if (-1 == bind(fd, (struct sockaddr *)&server, socklen)) { - OIC_LOG(ERROR, TAG, "bind() error"); + OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno)); goto exit; } - if (listen(g_acceptServerFD, caglobals.tcp.listenBacklog) != 0) + if (listen(fd, caglobals.tcp.listenBacklog) != 0) { OIC_LOG(ERROR, TAG, "listen() error"); goto exit; } - CHECKFD(g_acceptServerFD); + if (!sock->port) // return the assigned port + { + if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen)) + { + OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno)); + goto exit; + } + sock->port = ntohs(family == AF_INET6 ? + ((struct sockaddr_in6 *)&server)->sin6_port : + ((struct sockaddr_in *)&server)->sin_port); + } - return CA_STATUS_OK; + return fd; exit: - if (g_acceptServerFD >= 0) + if (fd >= 0) { - close(g_acceptServerFD); - g_acceptServerFD = -1; + close(fd); } - return CA_STATUS_FAILED; + return -1; } static void CAInitializePipe(int *fds) @@ -529,6 +611,10 @@ CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool) { caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests } + if (!caglobals.tcp.ipv6tcpenabled) + { + caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests + } CAResult_t res = CATCPCreateMutex(); if (CA_STATUS_OK == res) @@ -550,12 +636,15 @@ CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool) if (caglobals.server) { - res = CACreateAcceptSocket(); - if (CA_STATUS_OK != res) - { - OIC_LOG(ERROR, TAG, "failed to create accept socket"); - return res; - } + 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); + + 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", + caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port); } // create pipe for fast shutdown @@ -609,10 +698,16 @@ void CATCPStopServer() // mutex unlock ca_mutex_unlock(g_mutexObjectList); - if (-1 != g_acceptServerFD) + if (-1 != caglobals.tcp.ipv4.fd) + { + close(caglobals.tcp.ipv4.fd); + caglobals.tcp.ipv4.fd = -1; + } + + if (-1 != caglobals.tcp.ipv6.fd) { - close(g_acceptServerFD); - g_acceptServerFD = -1; + close(caglobals.tcp.ipv6.fd); + caglobals.tcp.ipv6.fd = -1; } CATCPDisconnectAll(); @@ -625,9 +720,9 @@ void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback) g_packetReceivedCallback = callback; } -void CATCPSetKeepAliveCallback(CATCPKeepAliveHandleCallback keepaliveHandler) +void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler) { - g_keepaliveCallback = keepaliveHandler; + g_connectionCallback = connHandler; } static size_t CACheckPayloadLength(const void *data, size_t dlen) @@ -666,8 +761,8 @@ static size_t CACheckPayloadLength(const void *data, size_t dlen) return payloadLen; } -static void sendData(const CAEndpoint_t *endpoint, - const void *data, size_t dlen) +static void sendData(const CAEndpoint_t *endpoint, const void *data, + size_t dlen, const char *fam) { // #1. get TCP Server object from list size_t index = 0; @@ -723,7 +818,7 @@ static void sendData(const CAEndpoint_t *endpoint, remainLen -= len; } while (remainLen > 0); - OIC_LOG_V(INFO, TAG, "unicast ipv4tcp sendTo is successful: %zu bytes", dlen); + OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen); } void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen, @@ -734,9 +829,13 @@ void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen, if (!isMulticast) { - if (caglobals.tcp.ipv4tcpenabled && (endpoint->adapter & CA_ADAPTER_TCP)) + if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6)) + { + sendData(endpoint, data, datalen, "ipv6"); + } + if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4)) { - sendData(endpoint, data, datalen); + sendData(endpoint, data, datalen, "ipv4"); } } } @@ -761,42 +860,43 @@ 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; // #2. create the socket and connect to TCP server - if (caglobals.tcp.ipv4tcpenabled) + int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET; + int fd = CATCPCreateSocket(family, svritem); + if (-1 == fd) + { + OICFree(svritem); + return NULL; + } + + // #3. add TCP connection info to list + svritem->fd = fd; + ca_mutex_lock(g_mutexObjectList); + if (caglobals.tcp.svrlist) { - int fd = CATCPCreateSocket(AF_INET, svritem); - if (-1 == fd) + bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem); + if (!res) { + OIC_LOG(ERROR, TAG, "u_arraylist_add failed."); + close(svritem->fd); OICFree(svritem); + ca_mutex_unlock(g_mutexObjectList); return NULL; } + } + ca_mutex_unlock(g_mutexObjectList); - // #3. add TCP connection info to list - svritem->fd = fd; - ca_mutex_lock(g_mutexObjectList); - if (caglobals.tcp.svrlist) - { - bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem); - if (!res) - { - OIC_LOG(ERROR, TAG, "u_arraylist_add failed."); - close(svritem->fd); - OICFree(svritem); - ca_mutex_unlock(g_mutexObjectList); - return NULL; - } - } - ca_mutex_unlock(g_mutexObjectList); - - CHECKFD(fd); + CHECKFD(fd); - // pass the connection information to RI for keepalive. - if (g_keepaliveCallback) - { - g_keepaliveCallback(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, true); - } + // pass the connection information to CA Common Layer. + if (g_connectionCallback) + { + g_connectionCallback(&(svritem->sep.endpoint), true); } return svritem; @@ -818,10 +918,10 @@ CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index) OICFree(svritem); ca_mutex_unlock(g_mutexObjectList); - // pass the connection information to RI for keepalive. - if (g_keepaliveCallback) + // pass the connection information to CA Common Layer. + if (g_connectionCallback) { - g_keepaliveCallback(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, false); + g_connectionCallback(&(svritem->sep.endpoint), false); } return CA_STATUS_OK; @@ -847,8 +947,7 @@ void CATCPDisconnectAll() ca_mutex_unlock(g_mutexObjectList); } -CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, - size_t *index) +CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index) { VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL); VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL); @@ -866,7 +965,8 @@ CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr)) - && (svritem->sep.endpoint.port == endpoint->port)) + && (svritem->sep.endpoint.port == endpoint->port) + && (svritem->sep.endpoint.flags & endpoint->flags)) { *index = i; return svritem; diff --git a/resource/csdk/connectivity/test/SConscript b/resource/csdk/connectivity/test/SConscript index 53b2d6e70..4867af304 100644 --- a/resource/csdk/connectivity/test/SConscript +++ b/resource/csdk/connectivity/test/SConscript @@ -18,12 +18,16 @@ # #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -Import('env') import os import os.path -catest_env = env.Clone() + +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +catest_env = gtest_env.Clone() src_dir = catest_env.get('SRC_DIR') +target_os = catest_env.get('TARGET_OS') +target_transport = catest_env.get('TARGET_TRANSPORT') ###################################################################### # Build flags @@ -34,7 +38,6 @@ catest_env.PrependUnique(CPPPATH = [ '../../stack/include', '../../extlibs/cjson', '../../../oc_logger/include', - '../../../../extlibs/gtest/gtest-1.7.0/include' ]) tmplist = catest_env['LINKFLAGS'][:] @@ -42,28 +45,27 @@ if '-lpthread' in tmplist: tmplist.remove('-lpthread') 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', +if target_os not in ['windows']: + catest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) +catest_env.AppendUnique(LIBPATH = [catest_env.get('BUILD_DIR')]) +catest_env.PrependUnique(LIBS = ['gtest', 'gtest_main']) +catest_env.PrependUnique(LIBS = ['octbstack', 'connectivity_abstraction', - 'coap', - 'gtest', - 'gtest_main']) - -target_os = env.get('TARGET_OS') + 'coap']) if target_os not in ['arduino', 'darwin', 'ios']: catest_env.AppendUnique(LIBS=['rt']) -if env.get('SECURED') == '1': - catest_env.AppendUnique(LIBS = ['tinydtls']) +if catest_env.get('SECURED') == '1': + catest_env.AppendUnique(LIBS = ['tinydtls']) -if env.get('LOGGING'): +if catest_env.get('LOGGING'): catest_env.AppendUnique(CPPDEFINES = ['TB_LOG']) +if target_os not in ['msys_nt', 'windows']: + catest_env.AppendUnique(LIBS = ['m']) + catest_env.PrependUnique(LIBS = ['pthread']) + ###################################################################### # Source files and Targets ###################################################################### @@ -76,10 +78,10 @@ catests = catest_env.Program('catests', ['catests.cpp', Alias("test", [catests]) -env.AppendTarget('test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': +catest_env.AppendTarget('test') +if catest_env.get('TEST') == '1': + if target_os in ['linux']: + catest_env.AppendENVPath('PATH', catest_env.get('BUILD_DIR')) from tools.scons.RunTest import * run_test(catest_env, 'resource_csdk_connectivity_test.memcheck', diff --git a/resource/csdk/connectivity/util/SConscript b/resource/csdk/connectivity/util/SConscript index 33e15f676..c89cb4c21 100644 --- a/resource/csdk/connectivity/util/SConscript +++ b/resource/csdk/connectivity/util/SConscript @@ -9,39 +9,25 @@ print "Reading util folder script" ca_os = env.get('TARGET_OS') ca_transport = env.get('TARGET_TRANSPORT') -src_dir = env.get('SRC_DIR') -root_dir = './../' -src_dir = './../util/src/' - -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') ]) - -if ca_os == 'android': - env.AppendUnique(CPPPATH = [ os.path.join(root_dir, 'util/src/android') ]) +target_os = env.get('TARGET_OS') +project_root = env.get('SRC_DIR') +root_dir = os.path.join(project_root, 'resource', 'csdk', 'connectivity') +src_dir = os.path.join(root_dir, 'util', 'src') ###################################################################### # Source files to build common for platforms ###################################################################### -env.AppendUnique(CA_SRC = [os.path.join(src_dir,'cautilinterface.c')]) - -if (('BLE' in ca_transport) or ('ALL' in ca_transport)): - if ca_os in ['linux', 'tizen', 'arduino']: - env.AppendUnique(CA_SRC = [ - os.path.join(src_dir,'camanager/' + ca_os + '/caleconnectionmanager.c')]) +env.AppendUnique(CA_SRC = [os.path.join('./../util/src/cautilinterface.c')]) - if ca_os == 'android': - env.AppendUnique(CA_SRC = [ - os.path.join(src_dir,'camanager/android/caleconnectionmanager.c'), - os.path.join(src_dir,'camanager/android/caleautoconnector.c'), - os.path.join(src_dir,'camanager/android/camanagerleutil.c'), - os.path.join(src_dir,'camanager/android/camanagerdevice.c')]) +if target_os == 'android': + if (('BLE' in ca_transport) or ('ALL' in ca_transport)): + env.AppendUnique(CA_SRC = [ + os.path.join(src_dir, 'camanager', 'android', 'caleconnectionmanager.c'), + os.path.join(src_dir, 'camanager', 'android', 'caleautoconnector.c'), + os.path.join(src_dir, 'camanager', 'android', 'camanagerleutil.c'), + os.path.join(src_dir, 'camanager', 'android', 'camanagerdevice.c')]) -if (('BT' in ca_transport) or ('ALL' in ca_transport)): - if ca_os == 'android': - env.AppendUnique(CA_SRC = [ - os.path.join(src_dir,'btpairing/android/cabtpairing.c')])
\ No newline at end of file + if (('BT' in ca_transport) or ('ALL' in ca_transport)): + env.AppendUnique(CA_SRC = [ + os.path.join(src_dir, 'btpairing' ,'android', 'cabtpairing.c')])
\ No newline at end of file diff --git a/resource/csdk/connectivity/util/inc/camanagerleinterface.h b/resource/csdk/connectivity/util/inc/camanagerleinterface.h index 9a175bfe5..fa3cb810a 100644 --- a/resource/csdk/connectivity/util/inc/camanagerleinterface.h +++ b/resource/csdk/connectivity/util/inc/camanagerleinterface.h @@ -48,18 +48,7 @@ CAResult_t CASetLEClientAutoConnectionDeviceInfo(); */ CAResult_t CAUnsetLEClientAutoConnectionDeviceInfo(); -/** - * Start advertise to receive request for scanning or connecting. - */ -void CAStartServerLEAdvertising(); - -/** - * Stop advertise to destroy advertiser. - */ -void CAStopServerLEAdvertising(); - -#ifdef __ANDROID__ -#ifdef LE_ADAPTER +#if defined(__ANDROID__) && defined(LE_ADAPTER) /** * initialize client connection manager * @param[in] env JNI interface pointer. @@ -78,7 +67,6 @@ CAResult_t CAManagerLEClientInitialize(JNIEnv *env, JavaVM *jvm, jobject context */ CAResult_t CAManagerLEClientTerminate(JNIEnv *env); #endif -#endif #ifdef __cplusplus } /* extern "C" */ diff --git a/resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.c b/resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.c index 76f439ce7..854da77d0 100644 --- a/resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.c +++ b/resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.c @@ -129,11 +129,13 @@ CAResult_t CAManagerStartAutoConnection(JNIEnv *env, jstring remote_le_address) ca_mutex_lock(g_connectRetryMutex); + CAResult_t res = CA_STATUS_OK; for (size_t retry_cnt = 0 ; retry_cnt < MAX_RETRY_COUNT ; retry_cnt++) { // there is retry logic 5 times when connectGatt call has failed // because BT adapter might be not ready yet. - if (NULL == CAManagerConnectGatt(env, remote_le_address)) + res = CAManagerConnectGatt(env, remote_le_address); + if (CA_STATUS_OK != res) { OIC_LOG_V(INFO, TAG, "retry will be started at least %d times after delay 1sec", MAX_RETRY_COUNT - retry_cnt - 1); @@ -153,13 +155,13 @@ CAResult_t CAManagerStartAutoConnection(JNIEnv *env, jstring remote_le_address) } ca_mutex_unlock(g_connectRetryMutex); OIC_LOG(DEBUG, TAG, "OUT - CAManagerStartAutoConnection"); - return CA_STATUS_OK; + return res; } -jobject CAManagerConnectGatt(JNIEnv *env, jstring remote_le_address) +CAResult_t CAManagerConnectGatt(JNIEnv *env, jstring remote_le_address) { - VERIFY_NON_NULL_RET(env, TAG, "env", NULL); - VERIFY_NON_NULL_RET(remote_le_address, TAG, "remote_le_address", NULL); + VERIFY_NON_NULL(env, TAG, "env"); + VERIFY_NON_NULL(remote_le_address, TAG, "remote_le_address"); OIC_LOG(DEBUG, TAG, "IN - CAManagerConnectGatt"); @@ -167,7 +169,7 @@ jobject CAManagerConnectGatt(JNIEnv *env, jstring remote_le_address) if (!jni_bluetooth) { OIC_LOG(ERROR, TAG, "jni_bluetooth is null"); - return NULL; + return CA_STATUS_FAILED; } if (!CAManagerIsDeviceBonded(env, jni_bluetooth)) @@ -177,18 +179,18 @@ jobject CAManagerConnectGatt(JNIEnv *env, jstring remote_le_address) // request to connection with AutoConnection Flag OIC_LOG(INFO, TAG, "request to gatt connection for auto connection"); - jobject newGatt = (jobject)CALEClientConnect(env, jni_bluetooth, JNI_TRUE); - if (NULL == newGatt) + CAResult_t res = CALEClientDirectConnect(env, jni_bluetooth, JNI_TRUE); + if (CA_STATUS_OK != res) { OIC_LOG(INFO, TAG, "re-connection will be started"); - return NULL; + return res; } // set flag auto connection is requested. CAManagerSetAutoConnectionFlag(env, remote_le_address, true); OIC_LOG(DEBUG, TAG, "OUT - CAManagerConnectGatt"); - return newGatt; + return CA_STATUS_OK; } CAResult_t CAManagerProcessRecovery(JNIEnv *env, uint16_t adapter_state) diff --git a/resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.h b/resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.h index 4875a889e..b7d88fe91 100644 --- a/resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.h +++ b/resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.h @@ -43,9 +43,9 @@ CAResult_t CAManagerStartAutoConnection(JNIEnv *env, jstring remote_le_address); * request connect gatt on client in adapter * @param[in] env JNI interface pointer. * @param[in] remote_le_address remote address. - * @return gatt profile object. + * @return ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h). */ -jobject CAManagerConnectGatt(JNIEnv *env, jstring remote_le_address); +CAResult_t CAManagerConnectGatt(JNIEnv *env, jstring remote_le_address); /** * initialize LE AutoConnection. diff --git a/resource/csdk/connectivity/util/src/camanager/android/caleconnectionmanager.c b/resource/csdk/connectivity/util/src/camanager/android/caleconnectionmanager.c index c4e43e386..3a11e2add 100644 --- a/resource/csdk/connectivity/util/src/camanager/android/caleconnectionmanager.c +++ b/resource/csdk/connectivity/util/src/camanager/android/caleconnectionmanager.c @@ -32,9 +32,6 @@ #define TAG "OIC_CA_MANAGER_LE" -static CAAdapterStateChangedCB g_adapterStateCB = NULL; -static CAConnectionStateChangedCB g_connStateCB = NULL; - static const jint SUPPORT_ADNROID_API_LEVEL = 18; static const jint AUTH_FAIL = 5; static const jint LINK_LOSS = 8; @@ -47,14 +44,6 @@ static JavaVM *g_jvm = NULL; static jobject g_context = NULL; static jobject g_connectedDeviceSet = NULL; -void CASetLENetworkMonitorCallbacks(CAAdapterStateChangedCB adapterStateCB, - CAConnectionStateChangedCB connStateCB) -{ - OIC_LOG(DEBUG, TAG, "CASetLENetworkMonitorCallbacks"); - - g_adapterStateCB = adapterStateCB; - g_connStateCB = connStateCB; -} CAResult_t CASetLEClientAutoConnectionDeviceInfo(const char* address) { @@ -296,10 +285,6 @@ Java_org_iotivity_ca_CaLeClientInterface_caManagerAdapterStateChangedCallback( if (state_on == state) { OIC_LOG(DEBUG, TAG, "AdapterStateChangedCallback : state_on"); - if (g_adapterStateCB) - { - g_adapterStateCB(CA_ADAPTER_GATT_BTLE, true); - } // when BT state is on. recovery flag has to be reset. CAManagerSetBTRecovery(false); @@ -324,10 +309,6 @@ Java_org_iotivity_ca_CaLeClientInterface_caManagerAdapterStateChangedCallback( else if (state_off == state) { OIC_LOG(DEBUG, TAG, "AdapterStateChangedCallback : state_off"); - if (g_adapterStateCB) - { - g_adapterStateCB(CA_ADAPTER_GATT_BTLE, false); - } // reset autoconnect flag for all target devices size_t length = CAManagerGetACDataLength(); @@ -452,13 +433,6 @@ Java_org_iotivity_ca_CaLeClientInterface_caManagerLeGattConnectionStateChangeCB( { OIC_LOG(DEBUG, TAG, "LE is disconnected"); - if (g_connStateCB) - { - OIC_LOG_V(DEBUG, TAG, "LE Disconnected state is %d, %s", newState, address); - g_connStateCB(CA_ADAPTER_GATT_BTLE, address, false); - OIC_LOG(DEBUG, TAG, "LE Disconnected state callback is called"); - } - if (!CAManagerIsMatchedACData(env, jni_address)) { OIC_LOG_V(DEBUG, TAG, "this[%s] is not target address for Auto Connection", @@ -635,7 +609,7 @@ Java_org_iotivity_ca_CaLeClientInterface_caManagerLeServicesDiscoveredCallback(J // next connection will be requested as JNI_TRUE flag // after first connection - CALEClientSetAutoConnectFlag(env, jni_str_entry, JNI_TRUE); + CALEClientSetFlagToState(env, jni_str_entry, CA_LE_AUTO_CONNECT_FLAG, JNI_TRUE); } else { @@ -646,12 +620,6 @@ Java_org_iotivity_ca_CaLeClientInterface_caManagerLeServicesDiscoveredCallback(J (*env)->DeleteLocalRef(env, jni_str_entry); } - if (g_connStateCB) - { - g_connStateCB(CA_ADAPTER_GATT_BTLE, address, true); - OIC_LOG(DEBUG, TAG, "LE Connected callback is called"); - } - (*env)->DeleteLocalRef(env, jni_cls_iterator); (*env)->DeleteLocalRef(env, jni_obj_iter); (*env)->DeleteLocalRef(env, jni_cls_set); diff --git a/resource/csdk/connectivity/util/src/camanager/arduino/caleconnectionmanager.c b/resource/csdk/connectivity/util/src/camanager/arduino/caleconnectionmanager.c deleted file mode 100644 index 33f7648b0..000000000 --- a/resource/csdk/connectivity/util/src/camanager/arduino/caleconnectionmanager.c +++ /dev/null @@ -1,61 +0,0 @@ -/* **************************************************************** - * - * 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 "camanagerleinterface.h" -#include "cacommon.h" -#include "logger.h" - -#define TAG "OIC_CA_MANAGER_AR_LE" - -static CAAdapterStateChangedCB g_adapterStateCB = NULL; -static CAConnectionStateChangedCB g_connStateCB = NULL; - -void CASetLENetworkMonitorCallbacks(CAAdapterStateChangedCB adapterStateCB, - CAConnectionStateChangedCB connStateCB) -{ - OIC_LOG(DEBUG, TAG, "CASetLENetworkMonitorCallbacks"); - - g_adapterStateCB = adapterStateCB; - g_connStateCB = connStateCB; -} - -CAResult_t CASetLEClientAutoConnectionDeviceInfo(const char * address) -{ - OIC_LOG(DEBUG, TAG, "CASetClientAutoConnectionDeviceInfo"); - (void)address; - return CA_NOT_SUPPORTED; -} - -CAResult_t CAUnsetLEClientAutoConnectionDeviceInfo(const char * address) -{ - OIC_LOG(DEBUG, TAG, "CAUnsetClientAutoConnectionDeviceInfo"); - (void)address; - return CA_NOT_SUPPORTED; -} - -void CAStartServerLEAdvertising() -{ - OIC_LOG(DEBUG, TAG, "CAStartServerLEAdvertising"); -} - -void CAStopServerLEAdvertising() -{ - OIC_LOG(DEBUG, TAG, "CAStopServerLEAdvertising"); -} diff --git a/resource/csdk/connectivity/util/src/camanager/linux/caleconnectionmanager.c b/resource/csdk/connectivity/util/src/camanager/linux/caleconnectionmanager.c deleted file mode 100644 index 98f336e74..000000000 --- a/resource/csdk/connectivity/util/src/camanager/linux/caleconnectionmanager.c +++ /dev/null @@ -1,61 +0,0 @@ -/* **************************************************************** - * - * 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 "camanagerleinterface.h" -#include "cacommon.h" -#include "logger.h" - -#define TAG "OIC_CA_MANAGER_LI_LE" - -static CAAdapterStateChangedCB g_adapterStateCB = NULL; -static CAConnectionStateChangedCB g_connStateCB = NULL; - -void CASetLENetworkMonitorCallbacks(CAAdapterStateChangedCB adapterStateCB, - CAConnectionStateChangedCB connStateCB) -{ - OIC_LOG(DEBUG, TAG, "CASetLENetworkMonitorCallbacks"); - - g_adapterStateCB = adapterStateCB; - g_connStateCB = connStateCB; -} - -CAResult_t CASetLEClientAutoConnectionDeviceInfo(const char * address) -{ - OIC_LOG(DEBUG, TAG, "CASetLEClientAutoConnectionDeviceInfo"); - (void)address; - return CA_NOT_SUPPORTED; -} - -CAResult_t CAUnsetLEClientAutoConnectionDeviceInfo(const char * address) -{ - OIC_LOG(DEBUG, TAG, "CAUnsetLEClientAutoConnectionDeviceInfo"); - (void)address; - return CA_NOT_SUPPORTED; -} - -void CAStartServerLEAdvertising() -{ - OIC_LOG(DEBUG, TAG, "CAStartServerLEAdvertising"); -} - -void CAStopServerLEAdvertising() -{ - OIC_LOG(DEBUG, TAG, "CAStopServerLEAdvertising"); -} diff --git a/resource/csdk/connectivity/util/src/camanager/tizen/caleconnectionmanager.c b/resource/csdk/connectivity/util/src/camanager/tizen/caleconnectionmanager.c deleted file mode 100644 index cc196f27b..000000000 --- a/resource/csdk/connectivity/util/src/camanager/tizen/caleconnectionmanager.c +++ /dev/null @@ -1,144 +0,0 @@ -/* **************************************************************** - * - * 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 <bluetooth.h> -#include <bluetooth_type.h> -#include <bluetooth_internal.h> - -#include "camanagerleinterface.h" -#include "cacommon.h" -#include "camessagehandler.h" -#include "caleserver.h" -#include "cagattservice.h" -#include "logger.h" - -#define TAG "OIC_CA_MANAGER_TZ_LE" - -static CAAdapterStateChangedCB g_adapterStateCB = NULL; -static CAConnectionStateChangedCB g_connStateCB = NULL; - -static void CAManagerAdapterMonitorHandler(const CAEndpoint_t *info, CANetworkStatus_t status); -static void CAManagerConnectionMonitorHandler(CATransportAdapter_t adapter, - const char *remoteAddress, bool connected); - -void CASetLENetworkMonitorCallbacks(CAAdapterStateChangedCB adapterStateCB, - CAConnectionStateChangedCB connStateCB) -{ - OIC_LOG(DEBUG, TAG, "CASetLENetworkMonitorCallbacks"); - - g_adapterStateCB = adapterStateCB; - CASetNetworkMonitorCallback(CAManagerAdapterMonitorHandler); - - g_connStateCB = connStateCB; - CASetLEConnectionStateChangedCallback(CAManagerConnectionMonitorHandler); -} - -void CAStartServerLEAdvertising() -{ - OIC_LOG(DEBUG, TAG, "CAStartServerLEAdvertising"); - - CAResult_t res = CALEStartAdvertise(CA_GATT_SERVICE_UUID); - if (CA_STATUS_OK != res) - { - OIC_LOG_V(ERROR, TAG, "Failed to start le advertising [%d]", res); - return; - } -} - -void CAStopServerLEAdvertising() -{ - OIC_LOG(DEBUG, TAG, "CAStopServerLEAdvertising"); - - CAResult_t res = CALEStopAdvertise(); - if (CA_STATUS_OK != res) - { - OIC_LOG_V(ERROR, TAG, "Failed to stop le advertising [%d]", res); - return; - } -} - -CAResult_t CASetLEClientAutoConnectionDeviceInfo(const char * address) -{ - OIC_LOG(DEBUG, TAG, "CASetLEClientAutoConnectionDeviceInfo"); - (void)address; - return CA_NOT_SUPPORTED; -} - -CAResult_t CAUnsetLEClientAutoConnectionDeviceInfo(const char * address) -{ - OIC_LOG(DEBUG, TAG, "CAUnsetLEClientAutoConnectionDeviceInfo"); - (void)address; - return CA_NOT_SUPPORTED; -} - -static void CAManagerAdapterMonitorHandler(const CAEndpoint_t *info, CANetworkStatus_t status) -{ - if (CA_INTERFACE_DOWN == status) - { - if (info && g_adapterStateCB) - { - g_adapterStateCB(info->adapter, false); - OIC_LOG(DEBUG, TAG, "Pass the disabled adapter state to upper layer"); - } - } - else if (CA_INTERFACE_UP == status) - { - if (info && g_adapterStateCB) - { - g_adapterStateCB(info->adapter, true); - OIC_LOG(DEBUG, TAG, "Pass the enabled adapter state to upper layer"); - } - } -} - -static void CAManagerConnectionMonitorHandler(CATransportAdapter_t adapter, - const char *remoteAddress, bool connected) -{ - (void)adapter; - - if (!remoteAddress) - { - OIC_LOG(ERROR, TAG, "remoteAddress is NULL"); - return; - } - - if (connected) - { - if (g_connStateCB) - { - g_connStateCB(CA_ADAPTER_GATT_BTLE, remoteAddress, true); - OIC_LOG(DEBUG, TAG, "Pass the connected device info to upper layer"); - - // stop le advertising - CAStopServerLEAdvertising(); - } - } - else - { - if (g_connStateCB) - { - g_connStateCB(CA_ADAPTER_GATT_BTLE, remoteAddress, false); - OIC_LOG(DEBUG, TAG, "Pass the disconnected device info to upper layer"); - - // start le advertising to receive new connection request. - CAStartServerLEAdvertising(); - } - } -} diff --git a/resource/csdk/connectivity/util/src/cautilinterface.c b/resource/csdk/connectivity/util/src/cautilinterface.c index 83513f775..046ace4a9 100644 --- a/resource/csdk/connectivity/util/src/cautilinterface.c +++ b/resource/csdk/connectivity/util/src/cautilinterface.c @@ -21,33 +21,80 @@ #include "camanagerleinterface.h" #include "cabtpairinginterface.h" #include "cautilinterface.h" - +#include "cainterfacecontroller.h" #include "cacommon.h" #include "logger.h" #define TAG "OIC_CA_COMMON_UTILS" +static CAAdapterStateChangedCB g_adapterStateCB = NULL; +static CAConnectionStateChangedCB g_connStateCB = NULL; + +static void CAManagerAdapterMonitorHandler(CATransportAdapter_t adapter, + CANetworkStatus_t status) +{ + if (CA_INTERFACE_DOWN == status) + { + if (g_adapterStateCB) + { + g_adapterStateCB(adapter, false); + OIC_LOG(DEBUG, TAG, "Pass the disabled adapter state to upper layer"); + } + } + else if (CA_INTERFACE_UP == status) + { + if (g_adapterStateCB) + { + g_adapterStateCB(adapter, true); + OIC_LOG(DEBUG, TAG, "Pass the enabled adapter state to upper layer"); + } + } +} + +static void CAManagerConnectionMonitorHandler(const CAEndpoint_t *info, bool isConnected) +{ + if (!info || !info->addr) + { + OIC_LOG(ERROR, TAG, "remoteAddress is NULL"); + return; + } + + if (isConnected) + { + if (g_connStateCB) + { + g_connStateCB(info->adapter, info->addr, isConnected); + OIC_LOG(DEBUG, TAG, "Pass the connected device info to upper layer"); + } + } + else + { + if (g_connStateCB) + { + g_connStateCB(info->adapter, info->addr, isConnected); + OIC_LOG(DEBUG, TAG, "Pass the disconnected device info to upper layer"); + } + } +} + CAResult_t CARegisterNetworkMonitorHandler(CAAdapterStateChangedCB adapterStateCB, CAConnectionStateChangedCB connStateCB) { OIC_LOG(DEBUG, TAG, "CARegisterNetworkMonitorHandler"); -#ifdef LE_ADAPTER - CASetLENetworkMonitorCallbacks(adapterStateCB, connStateCB); - return CA_STATUS_OK; -#else - (void)adapterStateCB; - (void)connStateCB; - return CA_NOT_SUPPORTED; -#endif + g_adapterStateCB = adapterStateCB; + g_connStateCB = connStateCB; + CASetNetworkMonitorCallbacks(CAManagerAdapterMonitorHandler, + CAManagerConnectionMonitorHandler); + return CA_STATUS_OK; } CAResult_t CASetAutoConnectionDeviceInfo(const char *address) { OIC_LOG(DEBUG, TAG, "CASetAutoConnectionDeviceInfo"); -#ifdef LE_ADAPTER +#if defined(__ANDROID__) && defined(LE_ADAPTER) return CASetLEClientAutoConnectionDeviceInfo(address); #else (void)address; @@ -59,7 +106,7 @@ CAResult_t CAUnsetAutoConnectionDeviceInfo(const char *address) { OIC_LOG(DEBUG, TAG, "CAUnsetAutoConnectionDeviceInfo"); -#ifdef LE_ADAPTER +#if defined(__ANDROID__) && defined(LE_ADAPTER) return CAUnsetLEClientAutoConnectionDeviceInfo(address); #else (void)address; diff --git a/resource/csdk/logger/include/logger.h b/resource/csdk/logger/include/logger.h index fcab19307..92b941b09 100644 --- a/resource/csdk/logger/include/logger.h +++ b/resource/csdk/logger/include/logger.h @@ -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> @@ -77,8 +77,18 @@ typedef enum { #endif #ifdef __TIZEN__ -#define OCLog(level,tag,mes) -#define OCLogv(level,tag,fmt,args...) +/** + * Output the contents of the specified buffer (in hex) with the specified priority level. + * + * @param[in] level DEBUG, INFO, WARNING, ERROR, FATAL + * @param[in] tag Module name + * @param[in] buffer pointer to buffer of bytes + * @param[in] bufferSize max number of byte in buffer + */ +void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize); + +#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__) /** * Configure logger to use a context that defines a custom logger function @@ -183,7 +193,8 @@ typedef enum { #define OIC_LOG(level,tag,mes) LOG_(LOG_ID_MAIN, (level), (tag), mes) #define OIC_LOG_V(level,tag,fmt,args...) LOG_(LOG_ID_MAIN, level, tag, fmt, ##args) -#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize) +#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)\ + OCLogBuffer((level), (tag), (buffer), (bufferSize)) #else // These macros are defined for Linux, Android, and Arduino diff --git a/resource/csdk/logger/src/logger.c b/resource/csdk/logger/src/logger.c index 295ac5f29..cc30d58b3 100644 --- a/resource/csdk/logger/src/logger.c +++ b/resource/csdk/logger/src/logger.c @@ -100,8 +100,48 @@ static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1; #endif #endif // __ANDROID__ - #ifndef ARDUINO + +/** + * Output the contents of the specified buffer (in hex) with the specified priority level. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param buffer - pointer to buffer of bytes + * @param bufferSize - max number of byte in buffer + */ +void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize) +{ + if (!buffer || !tag || (bufferSize == 0)) + { + return; + } + + // No idea why the static initialization won't work here, it seems the compiler is convinced + // that this is a variable-sized object. + char lineBuffer[LINE_BUFFER_SIZE]; + memset(lineBuffer, 0, sizeof lineBuffer); + int lineIndex = 0; + int i; + for (i = 0; i < bufferSize; i++) + { + // Format the buffer data into a line + snprintf(&lineBuffer[lineIndex*3], sizeof(lineBuffer)-lineIndex*3, "%02X ", buffer[i]); + lineIndex++; + // Output 16 values per line + if (((i+1)%16) == 0) + { + OCLogv(level, tag, "%s", lineBuffer); + memset(lineBuffer, 0, sizeof lineBuffer); + lineIndex = 0; + } + } + // Output last values in the line, if any + if (bufferSize % 16) + { + OCLogv(level, tag, "%s", lineBuffer); + } +} #ifndef __TIZEN__ void OCLogConfig(oc_log_ctx_t *ctx) { @@ -203,47 +243,6 @@ void OCLog(LogLevel level, const char * tag, const char * logStr) } #endif } - -/** - * Output the contents of the specified buffer (in hex) with the specified priority level. - * - * @param level - DEBUG, INFO, WARNING, ERROR, FATAL - * @param tag - Module name - * @param buffer - pointer to buffer of bytes - * @param bufferSize - max number of byte in buffer - */ -void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize) -{ - if (!buffer || !tag || (bufferSize == 0)) - { - return; - } - - // No idea why the static initialization won't work here, it seems the compiler is convinced - // that this is a variable-sized object. - char lineBuffer[LINE_BUFFER_SIZE]; - memset(lineBuffer, 0, sizeof lineBuffer); - int lineIndex = 0; - int i; - for (i = 0; i < bufferSize; i++) - { - // Format the buffer data into a line - snprintf(&lineBuffer[lineIndex*3], sizeof(lineBuffer)-lineIndex*3, "%02X ", buffer[i]); - lineIndex++; - // Output 16 values per line - if (((i+1)%16) == 0) - { - OCLog(level, tag, lineBuffer); - memset(lineBuffer, 0, sizeof lineBuffer); - lineIndex = 0; - } - } - // Output last values in the line, if any - if (bufferSize % 16) - { - OCLog(level, tag, lineBuffer); - } -} #endif //__TIZEN__ #endif //ARDUINO #ifdef ARDUINO diff --git a/resource/csdk/security/SConscript b/resource/csdk/security/SConscript index ccfcda091..4868fdf0e 100644..100755 --- a/resource/csdk/security/SConscript +++ b/resource/csdk/security/SConscript @@ -1,3 +1,4 @@ +# -*- mode: python; python-indent-offset: 4; indent-tabs-mode: nil -*- # //****************************************************************** # // # // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved. @@ -22,9 +23,10 @@ ## Import('env') +import os lib_env = env.Clone() -SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env') +SConscript('#resource/third_party_libs.scons', 'lib_env') libocsrm_env = lib_env.Clone() @@ -65,24 +67,24 @@ if target_os not in ['windows', 'winrt']: libocsrm_env.AppendUnique(CFLAGS = ['-Wall']) libocsrm_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) -libocsrm_env.AppendUnique(LIBS = ['coap', 'm']) 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 ['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'): - libocsrm_env.AppendUnique(CPPDEFINES = ['TB_LOG']) - if env.get('DTLS_WITH_X509') == '1': libocsrm_env.AppendUnique(CPPDEFINES = ['__WITH_X509__']) +if libocsrm_env.get('LOGGING'): + libocsrm_env.AppendUnique(CPPDEFINES = ['TB_LOG']) + ###################################################################### # Source files and Targets ###################################################################### diff --git a/resource/csdk/security/include/internal/aclresource.h b/resource/csdk/security/include/internal/aclresource.h index 5f1ac9de3..7daf51ff4 100644 --- a/resource/csdk/security/include/internal/aclresource.h +++ b/resource/csdk/security/include/internal/aclresource.h @@ -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. @@ -63,6 +63,19 @@ const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t ** OCStackResult AclToCBORPayload(const OicSecAcl_t * acl, uint8_t **outPayload, size_t *size); /** + * This method removes ACE for the subject and resource from the ACL + * + * @param subject of the ACE + * @param resource of the ACE + * + * @return + * ::OC_STACK_RESOURCE_DELETED on success + * ::OC_STACK_NO_RESOURCE on failure to find the appropriate ACE + * ::OC_STACK_INVALID_PARAM on invalid parameter + */ +OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource); + +/** * This function deletes ACL data. * * @param acl instance of @ref OicSecAcl_t structure to be deleted. @@ -70,6 +83,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 +101,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 diff --git a/resource/csdk/security/include/internal/amsmgr.h b/resource/csdk/security/include/internal/amsmgr.h index e07b44290..d8e761426 100644 --- a/resource/csdk/security/include/internal/amsmgr.h +++ b/resource/csdk/security/include/internal/amsmgr.h @@ -95,19 +95,13 @@ OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context, * ::OC_STACK_ERROR, If unable to successfully send unicast ACL request due to error. * */ + OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivityType connType, uint16_t securedPort); /* - * Cleanup CARequestInfo_t object. - * - * @param requestInfo is the pointer to @ref CARequestInfo_t. - */ -void FreeCARequestInfo(CARequestInfo_t *requestInfo); - -/* * This method is used by Policy engine to checks Amacl resource. * If Amacl is found then it fills up context->amsMgrContext->amsDeviceId * with amsID of the Amacl else leaves it empty. diff --git a/resource/csdk/security/include/internal/credresource.h b/resource/csdk/security/include/internal/credresource.h index 7e1291267..a8d3e9fa4 100644 --- a/resource/csdk/security/include/internal/credresource.h +++ b/resource/csdk/security/include/internal/credresource.h @@ -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. diff --git a/resource/csdk/security/include/internal/crlresource.h b/resource/csdk/security/include/internal/crlresource.h index 454bec7cc..3e98f8cc1 100644 --- a/resource/csdk/security/include/internal/crlresource.h +++ b/resource/csdk/security/include/internal/crlresource.h @@ -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. diff --git a/resource/csdk/security/include/internal/directpairing.h b/resource/csdk/security/include/internal/directpairing.h index e884c9af8..328523d0d 100644 --- a/resource/csdk/security/include/internal/directpairing.h +++ b/resource/csdk/security/include/internal/directpairing.h @@ -43,6 +43,7 @@ OCStackResult DPDeviceDiscovery(unsigned short waittime); /**
* Start direct-pairing processes.
*
+ * @param[in] ctx user context passed back with resultCallback.
* @param[in] peer target device to establish direct-pairing.
* @param[in] pmSel selected pairing method.
* @param[in] pinNumber secret value for dtls connection.
@@ -50,8 +51,8 @@ OCStackResult DPDeviceDiscovery(unsigned short waittime); *
* @return OC_STACK_OK on success otherwise error.
*/
-OCStackResult DPDirectPairing(OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, char *pinNumber,
- OCDirectPairingResultCB resultCallback);
+OCStackResult DPDirectPairing(void *ctx, OCDirectPairingDev_t* peer, OicSecPrm_t pmSel,
+ char *pinNumber, OCDirectPairingResultCB resultCallback);
/**
* This function returns discovered devices list in direct-pairing discovery
diff --git a/resource/csdk/security/include/internal/doxmresource.h b/resource/csdk/security/include/internal/doxmresource.h index d6f98afac..f63a2b109 100644..100755 --- a/resource/csdk/security/include/internal/doxmresource.h +++ b/resource/csdk/security/include/internal/doxmresource.h @@ -72,11 +72,12 @@ OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size, * @note Caller needs to invoke OCFree after done using the return pointer. * @param cborPayload is the payload of the cbor. * @param cborSize is the size of the cbor payload. Passed parameter should not be NULL. + * @param rwOnly indicates whether convertingpayload has all properties or read-write properties only. * * @return ::OC_STACK_OK for Success, otherwise some error value. */ OCStackResult DoxmToCBORPayload(const OicSecDoxm_t * doxm, uint8_t **cborPayload, - size_t *cborSize); + size_t *cborSize, bool rwOnly); /** * This method returns the SRM device ID for this device. diff --git a/resource/csdk/security/include/internal/psinterface.h b/resource/csdk/security/include/internal/psinterface.h index 34a78220d..493690a25 100644 --- a/resource/csdk/security/include/internal/psinterface.h +++ b/resource/csdk/security/include/internal/psinterface.h @@ -71,4 +71,21 @@ OCStackResult GetSecureVirtualDatabaseFromPS(const char *rsrcName, uint8_t **dat */ OCStackResult UpdateSecureResourceInPS(const char* rsrcName, uint8_t* cborPayload, size_t size); +/** + * This method resets the secure resources according to the reset profile. + * + * @return ::OC_STACK_OK for Success, otherwise some error value + */ +OCStackResult ResetSecureResourceInPS(void); + +/** + * This method creates the reset profile from the persistent storage. + * The reset profile is the copy of the initial state of SVR resources + * when secure resources are initiated at first. + * In remote reset, the SVR will be reset according to the reset profile. + * + * @return ::OC_STACK_OK for Success, otherwise some error value + */ +OCStackResult CreateResetProfile(void); + #endif //IOTVT_SRM_PSI_H diff --git a/resource/csdk/security/include/internal/pstatresource.h b/resource/csdk/security/include/internal/pstatresource.h index a36d1427a..c603f34c2 100644 --- a/resource/csdk/security/include/internal/pstatresource.h +++ b/resource/csdk/security/include/internal/pstatresource.h @@ -50,7 +50,7 @@ OCStackResult DeInitPstatResource(); * @return ::OC_STACK_OK for Success, otherwise some error value. */ OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **cborPayload, - size_t *cborSize); + size_t *cborSize, bool writableOnly); /** * This method converts cbor into PSTAT data. diff --git a/resource/csdk/security/include/internal/srmresourcestrings.h b/resource/csdk/security/include/internal/srmresourcestrings.h index c1900acc5..d9e8de8d9 100644 --- a/resource/csdk/security/include/internal/srmresourcestrings.h +++ b/resource/csdk/security/include/internal/srmresourcestrings.h @@ -23,9 +23,12 @@ #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; @@ -86,6 +89,9 @@ extern const char * OIC_RSRC_TYPE_SEC_VER; extern const char * OIC_RSRC_VER_URI; extern const char * OIC_JSON_VER_NAME; +//reset profile +extern const char * OIC_JSON_RESET_PF_NAME; + extern const char * OIC_JSON_SUBJECT_NAME; extern const char * OIC_JSON_SUBJECTID_NAME; extern const char * OIC_JSON_RESOURCES_NAME; @@ -110,6 +116,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 +173,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 diff --git a/resource/csdk/security/include/securevirtualresourcetypes.h b/resource/csdk/security/include/securevirtualresourcetypes.h index 786658e03..7b1673959 100644 --- a/resource/csdk/security/include/securevirtualresourcetypes.h +++ b/resource/csdk/security/include/securevirtualresourcetypes.h @@ -162,6 +162,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 +267,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 +321,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 +363,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 }; /** diff --git a/resource/csdk/security/provisioning/SConscript b/resource/csdk/security/provisioning/SConscript index 9cc456fde..7b3f56e12 100644..100755 --- a/resource/csdk/security/provisioning/SConscript +++ b/resource/csdk/security/provisioning/SConscript @@ -65,7 +65,7 @@ if target_os not in ['windows', 'winrt']: # 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(LIBS = ['dl', 'pthread']) provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) @@ -92,6 +92,7 @@ if target_os == 'android': if target_os in ['darwin', 'ios']: provisioning_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE']) +provisioning_env.AppendUnique(CPPDEFINES = ['TB_LOG']) ###################################################################### # Source files and Targets ###################################################################### diff --git a/resource/csdk/security/provisioning/ck_manager/sample/Door_sample.cpp b/resource/csdk/security/provisioning/ck_manager/sample/Door_sample.cpp index 316d0da72..280726370 100644 --- a/resource/csdk/security/provisioning/ck_manager/sample/Door_sample.cpp +++ b/resource/csdk/security/provisioning/ck_manager/sample/Door_sample.cpp @@ -442,7 +442,7 @@ void SendGetRequest() initAddress(); - char szQueryUri[64] = { '\0'}; + char szQueryUri[MAX_QUERY_LENGTH] = { '\0'}; OCDoHandle handle; OCCallbackData cbData; cbData.cb = getReqCB; @@ -462,7 +462,7 @@ void SendGetRequest() void *input_function(void * /*data*/) { char input; - char szQueryUri[64] = { 0 }; + char szQueryUri[MAX_QUERY_LENGTH] = { 0 }; OCDoHandle handle; OCCallbackData cbData; cbData.cb = discoveryReqCB; diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat Binary files differindex bf440f233..fbe36db7d 100755..100644 --- a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat +++ b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.json b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.json index 20062b4c4..6dcbdbf72 100755..100644 --- a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.json +++ b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.json @@ -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
@@ -50,32 +30,32 @@ {
"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/crl",
+ "href": "/oic/sec/cred",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.cred"],
+ "if": ["oic.if.baseline"]
},
{
- "href": "/oic/sec/cred",
+ "href": "/oic/sec/crl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.crl"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 6
@@ -100,6 +80,6 @@ "owned": false,
"deviceuuid": "646F6F72-4465-7669-6365-555549443030",
"rowneruuid": "646F6F72-4465-7669-6365-555549443030",
- "dpc": false
+ "x.org.iotivity.dpc": false
}
} diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat Binary files differindex 59f65e5f4..46eed498b 100755..100644 --- a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat +++ b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.json b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.json index a7598d48e..0bf43759d 100755..100644 --- a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.json +++ b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.json @@ -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
@@ -50,32 +30,32 @@ {
"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/crl",
+ "href": "/oic/sec/cred",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.cred"],
+ "if": ["oic.if.baseline"]
},
{
- "href": "/oic/sec/cred",
+ "href": "/oic/sec/crl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.crl"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 6
@@ -100,6 +80,6 @@ "owned": false,
"deviceuuid": "6C696768-7444-6576-6963-655555494430",
"rowneruuid": "6C696768-7444-6576-6963-655555494430",
- "dpc": false
+ "x.org.iotivity.dpc": false
}
} diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat Binary files differindex 6143d3258..ea814fde9 100755..100644 --- a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat +++ b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.json b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.json index 2e33796ea..f13ed088b 100755..100644 --- a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.json +++ b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.json @@ -8,32 +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/types/d",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/ad",
- "rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
}
],
"permission": 2
@@ -44,14 +30,14 @@ {
"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": 2
@@ -77,6 +63,6 @@ "deviceuuid": "61646D69-6E44-6576-6963-655575696430",
"devowneruuid": "61646D69-6E44-6576-6963-655575696430",
"rowneruuid": "61646D69-6E44-6576-6963-655575696430",
- "dpc": false
+ "x.org.iotivity.dpc": false
}
}
\ No newline at end of file diff --git a/resource/csdk/security/provisioning/ck_manager/sample/provisioningclient.c b/resource/csdk/security/provisioning/ck_manager/sample/provisioningclient.c index 91a761901..bf040deb8 100644 --- a/resource/csdk/security/provisioning/ck_manager/sample/provisioningclient.c +++ b/resource/csdk/security/provisioning/ck_manager/sample/provisioningclient.c @@ -37,6 +37,11 @@ #define MAX_URI_LENGTH (64) #define MAX_PERMISSION_LENGTH (5) +#define MAX_ACE_LENGTH (100) +#define MAX_INTERFACE_LENGTH (10) +#define MAX_RESOURCETYPE_LENGTH (10) +#define MAX_STRING_INPUT_BUFFER_SIZE (256) + #define CREATE (1) #define READ (2) #define UPDATE (4) @@ -64,29 +69,6 @@ typedef enum provisionCrlDone = 1 << 6 } StateManager; - -/** - * Perform cleanup for ACL - * @param[in] ACL - */ -static void deleteACL(OicSecAcl_t *acl) -{ - if (acl) - { - /* Clean Resources */ - for (size_t i = 0; i < (acl)->resourcesLen; i++) - { - OICFree((acl)->resources[i]); - } - OICFree((acl)->resources); - - /* Clean ACL node itself */ - OICFree((acl)); - - acl = NULL; - } -} - void deleteCrl(OicSecCrl_t *crl) { if (crl) @@ -178,9 +160,19 @@ static int InputACL(OicSecAcl_t *acl) char temp_id [UUID_LENGTH + 4] = {0,}; char temp_rsc[MAX_URI_LENGTH + 1] = {0,}; char temp_pms[MAX_PERMISSION_LENGTH + 1] = {0,}; + char input_buffer[MAX_STRING_INPUT_BUFFER_SIZE] = {0}; + OicSecAce_t* ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t)); + if(!ace) + { + printf("Failed to memory allocation\n"); + return -1; + } + LL_APPEND(acl->aces, ace); + printf("******************************************************************************\n"); printf("-Set ACL policy for target device\n"); printf("******************************************************************************\n"); + //Set Subject. printf("-URN identifying the subject\n"); printf("ex) doorDeviceUUID00 (16 Numbers except to '-')\n"); @@ -207,62 +199,135 @@ static int InputACL(OicSecAcl_t *acl) printf("Invalid input\n"); return -1; } - acl->subject.id[j++] = temp_id[i]; + ace->subjectuuid.id[j++] = temp_id[i]; } } //Set Resource. printf("Num. of Resource : \n"); - ret = scanf("%zu", &acl->resourcesLen); - if(-1 == ret) + size_t inputLen = 0; + ret = scanf("%zu", &inputLen); + if(-1 == ret || MAX_ACE_LENGTH < inputLen) { printf("Error while input\n"); return -1; } printf("-URI of resource\n"); printf("ex) /a/light (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 < inputLen; i++) { + OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t)); + if(!rsrc) + { + printf("Failed to memory allocation\n"); + return -1; + } + LL_APPEND(ace->resources, rsrc); + + //Input the resource URI for each resource printf("[%zu]Resource : ", i + 1); - char *ptr_tempRsc = NULL; - ret = scanf("%64ms", &ptr_tempRsc); + ret = scanf("%s", input_buffer); if (1==ret) { - OICStrcpy(temp_rsc, sizeof(temp_rsc), ptr_tempRsc); - OICFree(ptr_tempRsc); + rsrc->href = OICStrdup(input_buffer); + if(!rsrc->href) + { + printf("Failed to OICStrdup\n"); + return -1; + } } else { printf("Error while input\n"); return -1; } - acl->resources[i] = OICStrdup(temp_rsc); - if (NULL == acl->resources[i]) + //Input the interface name of resource + printf("Num. of Interface of [%s] (Max value : %d) : \n", rsrc->href, MAX_INTERFACE_LENGTH); + ret = scanf("%zu", &rsrc->interfaceLen); + if(-1 == ret || MAX_INTERFACE_LENGTH < rsrc->interfaceLen) + { + printf("Error while input\n"); + return -1; + } + + printf("-Interface of [%s] resource\n", rsrc->href); + printf("ex) oic.if.baseline (Max Length: 64 Byte )\n"); + rsrc->interfaces = (char**)OICCalloc(rsrc->interfaceLen, sizeof(char*)); + if(!rsrc->interfaces) + { + printf("Failed to memory allocation\n"); + return -1; + } + for(size_t j = 0; j < rsrc->interfaceLen; j++) + { + printf("Interface[%zu] : ", j + 1); + ret = scanf("%s", input_buffer); + if(1 == ret) + { + rsrc->interfaces[i] = OICStrdup(input_buffer); + if(!rsrc->interfaces[i]) + { + printf("Failed to OICStrdup\n"); + return -1; + } + } + else + { + printf("Error while input\n"); + return -1; + } + } + + //Input the resource type of resource + printf("Num. of ResourceType of [%s] (Max value : %d) : \n", rsrc->href, MAX_RESOURCETYPE_LENGTH); + ret = scanf("%zu", &rsrc->typeLen); + if(-1 == ret || MAX_RESOURCETYPE_LENGTH < rsrc->typeLen) + { + printf("Error while input\n"); + return -1; + } + + printf("-Resource Type of [%s] resource\n", rsrc->href); + printf("ex) oic.core (Max Length: 64 Byte )\n"); + rsrc->types = (char**)OICCalloc(rsrc->typeLen, sizeof(char*)); + if(!rsrc->types) { - OIC_LOG(ERROR, TAG, "Error while memory allocation"); + printf("Failed to memory allocation\n"); return -1; } + for(size_t j = 0; j < rsrc->typeLen; j++) + { + printf("Resource type[%zu] : ", j + 1); + ret = scanf("%s", input_buffer); + if(1 == ret) + { + rsrc->types[i] = OICStrdup(input_buffer); + if(!rsrc->types[i]) + { + printf("Failed to OICStrdup\n"); + return -1; + } + } + else + { + printf("Error while input\n"); + return -1; + } + } } + // Set Permission do { printf("-Set the permission(C,R,U,D,N)\n"); printf("ex) CRUDN, CRU_N,..(5 Charaters)\n"); printf("Permission : "); - char *ptr_temp_pms = NULL; - ret = scanf("%5ms", &ptr_temp_pms); + ret = scanf("%s", &input_buffer); if(1 == ret) { - OICStrcpy(temp_pms, sizeof(temp_pms), ptr_temp_pms); - OICFree(ptr_temp_pms); - + OICStrcpy(temp_pms, sizeof(temp_pms), input_buffer); } else { @@ -270,36 +335,13 @@ static int InputACL(OicSecAcl_t *acl) return -1; } } - while (0 != CalculateAclPermission(temp_pms, &(acl->permission)) ); - // Set Rowner - printf("-URN identifying the rowner\n"); - printf("ex) lightDeviceUUID0 (16 Numbers except to '-')\n"); + while (0 != CalculateAclPermission(temp_pms, &(ace->permission)) ); - printf("Rowner : "); - char *ptr_temp_id = NULL; - ret = scanf("%19ms", &ptr_temp_id); - if (1 == ret) - { - OICStrcpy(temp_id, sizeof(temp_id), ptr_temp_id); - OICFree(ptr_temp_id); - } - else - { - printf("Error while input\n"); - return -1; - } - j = 0; - for (int k = 0; temp_id[k] != '\0'; k++) - { - if (DASH != temp_id[k]) - { - acl->rownerID.id[j++] = temp_id[k]; - } - } return 0; } + //FILE *client_fopen(const char *path, const char *mode) FILE *client_fopen(const char* UNUSED_PARAM , const char *mode) { @@ -480,10 +522,15 @@ static int InputCRL(OicSecCrl_t *crlRes) PRINT_BYTE_ARRAY("CRL:\n",crl); CHECK_CALL(SetCertificateRevocationList, &crl); crlRes->CrlData = crl; - crlRes->ThisUpdate.data = uint8ThisUpdateTime; + crlRes->ThisUpdate.data = OICStrdup(uint8ThisUpdateTime); crlRes->ThisUpdate.len = DATE_LENGTH; crlRes->CrlId = 1; + if(NULL == crlRes->ThisUpdate.data) + { + printf("OICStrdup failed\n"); + return PKI_MEMORY_ALLOC_FAILED; + } FUNCTION_CLEAR( //OICFree(crl.data); @@ -738,7 +785,8 @@ int main() } error: - deleteACL(gAcl); + DeleteACLList(gAcl); + deleteCrl(gCrl); OCDeleteDiscoveredDevices(pDeviceList); OCDeleteDiscoveredDevices(pOwnedList); diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/SConscript b/resource/csdk/security/provisioning/ck_manager/unittest/SConscript index 6218806b0..ea6166b3c 100644 --- a/resource/csdk/security/provisioning/ck_manager/unittest/SConscript +++ b/resource/csdk/security/provisioning/ck_manager/unittest/SConscript @@ -17,16 +17,16 @@ # // limitations under the License. # // # //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -# -# SConscript file for Local PKI google tests - -Import('env') import os import os.path -pki_test_env = env.Clone() +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +pki_test_env = gtest_env.Clone() src_dir = pki_test_env.get('SRC_DIR') +build_dir = pki_test_env.get('BUILD_DIR') +target_os = pki_test_env.get('TARGET_OS') ###################################################################### # Build flags @@ -42,16 +42,15 @@ pki_test_env.PrependUnique(CPPPATH = ['../include/', '../../../../logger/include', '../../../../stack/include', '../../../../../oc_logger/include', - '../../../../../../extlibs/gtest/gtest-1.7.0/include', '../../../../../../extlibs/asn1cert', '../../../../../../extlibs/tinydtls', '../../../../../../extlibs/tinydtls/ecc', '../../../../../../extlibs/tinydtls/sha2' ]) -pki_test_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) -pki_test_env.AppendUnique(LIBS = ['pthread']) -pki_test_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) -pki_test_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs']) +if target_os not in ['windows']: + pki_test_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) + pki_test_env.AppendUnique(LIBS = ['pthread']) +pki_test_env.AppendUnique(LIBPATH = [pki_test_env.get('BUILD_DIR')]) pki_test_env.AppendUnique(LIBS = ['octbstack']) pki_test_env.AppendUnique(LIBS = ['CKManager']) @@ -59,42 +58,45 @@ pki_test_env.AppendUnique(LIBS = ['asn1']) pki_test_env.AppendUnique(LIBS = ['gtest']) pki_test_env.AppendUnique(LIBS = ['gtest_main']) -if env.get('SECURED') == '1': +if pki_test_env.get('SECURED') == '1': pki_test_env.AppendUnique(LIBS = ['tinydtls']) -if not env.get('RELEASE'): +if not pki_test_env.get('RELEASE'): pki_test_env.AppendUnique(CPPDEFINES = ['TB_LOG']) ###################################################################### # 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' -pki_test_env.Alias("install",env.Install( unittest_build_dir, [ unittest_src_dir + '01.der', +unittest_build_dir = os.path.join(build_dir, 'resource', 'csdk', 'security', 'provisioning', 'ck_manager', 'unittest') +unittest_build_dir = unittest_build_dir.encode('string_escape') +pki_test_env.AppendUnique(CPPDEFINES = ['SECURITY_BUILD_UNITTEST_DIR='+unittest_build_dir]) +pki_test_env.Alias("install", pki_test_env.Install( unittest_build_dir, [ unittest_src_dir + '01.der', unittest_src_dir + 'cacert.der', unittest_src_dir + 'capub.der', unittest_src_dir + 'cert_chain.dat', unittest_src_dir + 'chain.der', unittest_src_dir + 'CKMInfo.dat' ])) -env.AppendTarget('test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': - out_dir = env.get('BUILD_DIR') - result_dir = env.get('BUILD_DIR') + '/test_out/' +pki_test_env.AppendTarget('test') +if pki_test_env.get('TEST') == '1': + if target_os in ['linux']: + out_dir = pki_test_env.get('BUILD_DIR') + result_dir = os.path.join(pki_test_env.get('BUILD_DIR'), 'test_out') + os.sep if not os.path.isdir(result_dir): os.makedirs(result_dir) 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 index 000000000..66d6cb15c --- /dev/null +++ b/resource/csdk/security/provisioning/ck_manager/unittest/ckm_info_test.cpp @@ -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 index 000000000..93d0343f3 --- /dev/null +++ b/resource/csdk/security/provisioning/ck_manager/unittest/crl_generator_test.cpp @@ -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 index 000000000..c94f3c504 --- /dev/null +++ b/resource/csdk/security/provisioning/ck_manager/unittest/csr_generator_test.cpp @@ -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); + } +} diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/pki_test.cpp b/resource/csdk/security/provisioning/ck_manager/unittest/pki_test.cpp index e224b4273..649888a2a 100644 --- a/resource/csdk/security/provisioning/ck_manager/unittest/pki_test.cpp +++ b/resource/csdk/security/provisioning/ck_manager/unittest/pki_test.cpp @@ -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) diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat Binary files differindex 06454be2e..70e2b51d8 100644 --- a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat +++ b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.json b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.json index dbdee7749..5ac89c082 100644 --- a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.json +++ b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.json @@ -8,32 +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/types/d",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/ad",
- "rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
}
],
"permission": 2
@@ -44,26 +30,26 @@ {
"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": 7
@@ -94,6 +80,6 @@ "deviceuuid": "61646d69-6e44-6576-6963-655555494430",
"devowneruuid": "61646d69-6e44-6576-6963-655555494430",
"rowneruuid": "61646d69-6e44-6576-6963-655555494430",
- "dpc": false
+ "x.org.iotivity.dpc": false
}
}
\ No newline at end of file diff --git a/resource/csdk/security/provisioning/include/internal/credentialgenerator.h b/resource/csdk/security/provisioning/include/internal/credentialgenerator.h index 99fb37dc4..b87dd56ca 100644 --- a/resource/csdk/security/provisioning/include/internal/credentialgenerator.h +++ b/resource/csdk/security/provisioning/include/internal/credentialgenerator.h @@ -24,6 +24,10 @@ #include "ocstack.h" #include "securevirtualresourcetypes.h" +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + /** * Function to generate credentials according to the type. * diff --git a/resource/csdk/security/provisioning/include/internal/provisioningdatabasemanager.h b/resource/csdk/security/provisioning/include/internal/provisioningdatabasemanager.h index d37c48e47..c7c9483f5 100644 --- a/resource/csdk/security/provisioning/include/internal/provisioningdatabasemanager.h +++ b/resource/csdk/security/provisioning/include/internal/provisioningdatabasemanager.h @@ -39,6 +39,16 @@ extern "C" { OCStackResult PDMInit(const char* dbPath); /** + * This method is used by provisioning manager to check whether device is stale or not with PDM. + * + * @param[in] uuid information about the target device's uuid. + * @param[out] result true in case device is stale. + * + * @return OC_STACK_OK in case of success and other value otherwise. + */ +OCStackResult PDMIsDeviceStale(const OicUuid_t *uuid, bool *result); + +/** * This method is used by provisioning manager to check duplication of device's Device ID with * provisioning database. * diff --git a/resource/csdk/security/provisioning/include/internal/secureresourceprovider.h b/resource/csdk/security/provisioning/include/internal/secureresourceprovider.h index cc1f6897c..a378133b6 100644 --- a/resource/csdk/security/provisioning/include/internal/secureresourceprovider.h +++ b/resource/csdk/security/provisioning/include/internal/secureresourceprovider.h @@ -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. @@ -118,6 +140,55 @@ OCStackResult SRPRemoveDevice(void* ctx, const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback); +/* +* Function to device revocation +* This function will remove credential of target device from all devices in subnet. +* +* @param[in] ctx Application context would be returned in result callback +* @param[in] pOwnedDevList List of owned devices +* @param[in] pTargetDev Device information to be revoked. +* @param[in] resultCallback callback provided by API user, callback will be called when +* credential revocation is finished. +* @return OC_STACK_OK in case of success and other value otherwise. +* If OC_STACK_OK is returned, the caller of this API should wait for callback. +* OC_STACK_CONTINUE means operation is success but no request is need to be initiated. +*/ +OCStackResult SRPRemoveDeviceWithoutDiscovery(void* ctx, const OCProvisionDev_t* pOwnedDevList, + const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback); + +/* + * Function to sync-up credential and ACL of the target device. + * This function will remove credential and ACL of target device from all devices in subnet. + * + * @param[in] ctx Application context would be returned in result callback + * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds) + * @param[in] pTargetDev Device information to be revoked. + * @param[in] resultCallback callback provided by API user, callback will be called when + * credential revocation is finished. + * when there is an error, this user callback is called immediately. + * @return OC_STACK_OK in case of success and other value otherwise. + * If OC_STACK_OK is returned, the caller of this API should wait for callback. + * OC_STACK_CONTINUE means operation is success but no request is need to be initiated. + */ +OCStackResult SRPSyncDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery, + const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback); + +/* + * Function for remote reset + * This function will send pstat POST(modify) message to the target device + * to change current mode to reset state in order to initiate remote reset. + * + * @param[in] pTargetDev Device information to be revoked. + * @param[in] resultCallback callback provided by API user, callback will be called when + * credential revocation is finished. + * when there is an error, this user callback is called immediately. + * @return OC_STACK_OK in case of success and other value otherwise. + * If OC_STACK_OK is returned, the caller of this API should wait for callback. + * OC_STACK_CONTINUE means operation is success but no request is need to be initiated. + */ +OCStackResult SRPResetDevice(const OCProvisionDev_t* pTargetDev, + OCProvisionResultCB resultCallback); + #ifdef __cplusplus } #endif diff --git a/resource/csdk/security/provisioning/include/ocprovisioningmanager.h b/resource/csdk/security/provisioning/include/ocprovisioningmanager.h index 986c36021..a2c1f2a95 100644 --- a/resource/csdk/security/provisioning/include/ocprovisioningmanager.h +++ b/resource/csdk/security/provisioning/include/ocprovisioningmanager.h @@ -117,6 +117,30 @@ OCStackResult OCProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceIn OCProvisionResultCB resultCallback);
/**
+ * 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);
+/** + * 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); + +
+/**
* this function sends Direct-Pairing Configuration to a device.
*
* @param[in] ctx Application context would be returned in result callback.
@@ -178,7 +202,24 @@ OCStackResult OCRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
const OCProvisionDev_t* pTargetDev,
OCProvisionResultCB resultCallback);
-/** +
+/*
+* Function to device revocation
+* This function will remove credential of target device from all devices in subnet.
+*
+* @param[in] ctx Application context would be returned in result callback
+* @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
+* @param[in] pTargetDev Device information to be revoked.
+* @param[in] resultCallback callback provided by API user, callback will be called when
+* credential revocation is finished.
+ * @return OC_STACK_OK in case of success and other value otherwise.
+*/
+OCStackResult OCRemoveDeviceWithUuid(void* ctx,
+ unsigned short waitTimeForOwnedDeviceDiscovery,
+ const OicUuid_t* pTargetUuid,
+ OCProvisionResultCB resultCallback);
+
+/**
* API to get status of all the devices in current subnet. The status include endpoint information
* and doxm information which can be extracted duing owned and unowned discovery. Along with this
* information. The API will provide information about devices' status
diff --git a/resource/csdk/security/provisioning/include/pmtypes.h b/resource/csdk/security/provisioning/include/pmtypes.h index eede02d59..f6b7a7ab1 100644 --- a/resource/csdk/security/provisioning/include/pmtypes.h +++ b/resource/csdk/security/provisioning/include/pmtypes.h @@ -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 diff --git a/resource/csdk/security/provisioning/sample/SConscript b/resource/csdk/security/provisioning/sample/SConscript index a4f645d29..85b9019f8 100644 --- a/resource/csdk/security/provisioning/sample/SConscript +++ b/resource/csdk/security/provisioning/sample/SConscript @@ -22,6 +22,7 @@ Import('env') provisioning_env = env.Clone() +target_os = provisioning_env.get('TARGET_OS') ###################################################################### # Build flags @@ -45,11 +46,11 @@ provisioning_env.AppendUnique(CPPPATH = [ '../../../connectivity/lib/libcoap-4.1.1', '../../../connectivity/api' ]) - -provisioning_env.AppendUnique(CFLAGS = ['-D__WITH_DTLS__','-std=c99']) +provisioning_env.AppendUnique(CPPDEFINES = ['__WITH_DTLS__']) +provisioning_env.AppendUnique(CFLAGS = ['-std=c99']) provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread', '-fpermissive']) provisioning_env.AppendUnique(RPATH = [env.get('BUILD_DIR')]) -provisioning_env.AppendUnique(LIBS = ['-lpthread','-ldl']) +provisioning_env.AppendUnique(LIBS = ['dl','pthread']) provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) provisioning_env.PrependUnique(LIBS = ['ocpmapi','oc', 'oc_logger', 'ocsrm','m', 'octbstack', 'connectivity_abstraction', 'coap']) @@ -62,6 +63,9 @@ provisioning_env.ParseConfig('pkg-config --libs glib-2.0'); provisioning_env.AppendUnique(CPPDEFINES = ['TB_LOG']) +if target_os == 'tizen': + provisioning_env.AppendUnique(CPPDEFINES = ['__TIZEN__']) + ###################################################################### # Source files and Targets ###################################################################### diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_client.dat b/resource/csdk/security/provisioning/sample/oic_svr_db_client.dat Binary files differindex 781f65483..4b5b91881 100644 --- a/resource/csdk/security/provisioning/sample/oic_svr_db_client.dat +++ b/resource/csdk/security/provisioning/sample/oic_svr_db_client.dat diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_client.json b/resource/csdk/security/provisioning/sample/oic_svr_db_client.json index fb3c60918..6471926fd 100644 --- a/resource/csdk/security/provisioning/sample/oic_svr_db_client.json +++ b/resource/csdk/security/provisioning/sample/oic_svr_db_client.json @@ -8,38 +8,36 @@ {
"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": ""
- },
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
+ }
+ ],
+ "permission": 2
+ },
+ {
+ "subjectuuid": "*",
+ "resources": [
{
- "href": "/oic/ad",
+ "href": "/oic/sec/doxm",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.doxm"],
+ "if": ["oic.if.baseline"]
},
{
- "href": "/oic/sec/amacl",
+ "href": "/oic/sec/pstat",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.pstat"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 2
@@ -48,24 +46,24 @@ "subjectuuid": "*",
"resources": [
{
- "href": "/oic/sec/doxm",
+ "href": "/oic/sec/pconf",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.pconf"],
+ "if": ["oic.if.baseline"]
},
{
- "href": "/oic/sec/pstat",
+ "href": "/oic/sec/dpairing",
"rel": "",
- "rt": "",
- "if": ""
- }
+ "rt": ["oic.r.dpairing"],
+ "if": ["oic.if.baseline"]
+ }
],
"permission": 2
}
]
},
"rowneruuid" : "61646D69-6E44-6576-6963-655575696430"
- },
+ },
"pstat": {
"isop": true,
"cm": 0,
@@ -81,7 +79,7 @@ "sct": 1,
"owned": true,
"deviceuuid": "61646D69-6E44-6576-6963-655575696430",
- "dpc": false,
+ "x.org.iotivity.dpc": false,
"devowneruuid": "61646D69-6E44-6576-6963-655575696430",
"rowneruuid": "61646D69-6E44-6576-6963-655575696430"
}
diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.dat b/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.dat Binary files differindex 3796ce77b..c44c6b1b0 100644 --- a/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.dat +++ b/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.dat diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.json b/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.json index 20f2c368d..85c49cf6e 100644 --- a/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.json +++ b/resource/csdk/security/provisioning/sample/oic_svr_db_randompin_with_empty_deviceid.json @@ -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 @@ -50,26 +30,26 @@ { "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 @@ -80,14 +60,14 @@ { "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 @@ -125,6 +105,6 @@ "deviceuuid": "", "devowneruuid": "", "rowneruuid": "", - "dpc": true + "x.org.iotivity.dpc": true } } diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat b/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat Binary files differindex 4adbf4d4f..07b0d536a 100644 --- a/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat +++ b/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.json b/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.json index 59b56a750..8c7f34689 100644 --- a/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.json +++ b/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.json @@ -8,36 +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
@@ -48,26 +30,26 @@ {
"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
@@ -78,14 +60,14 @@ {
"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
@@ -96,8 +78,8 @@ {
"href": "/oic/sec/ver",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.ver"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 2
@@ -123,6 +105,6 @@ "deviceuuid": "6A757374-776F-726B-4465-765575696430",
"devowneruuid": "",
"rowneruuid": "6A757374-776F-726B-4465-765575696430",
- "dpc": true
+ "x.org.iotivity.dpc": true
}
-}
\ No newline at end of file +}
diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat b/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat Binary files differindex cfce7f825..6935b9c3c 100644 --- a/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat +++ b/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.json b/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.json index dc595bd9c..90b95345e 100644 --- a/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.json +++ b/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.json @@ -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
@@ -50,26 +30,26 @@ {
"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
@@ -80,14 +60,14 @@ {
"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
@@ -125,6 +105,6 @@ "deviceuuid": "72616E64-5069-6E44-6576-557569643030",
"devowneruuid": "",
"rowneruuid": "72616E64-5069-6E44-6576-557569643030",
- "dpc": true
+ "x.org.iotivity.dpc": true
}
}
diff --git a/resource/csdk/security/provisioning/sample/provisioningclient.c b/resource/csdk/security/provisioning/sample/provisioningclient.c index ab423b424..fa14f1485 100644 --- a/resource/csdk/security/provisioning/sample/provisioningclient.c +++ b/resource/csdk/security/provisioning/sample/provisioningclient.c @@ -22,6 +22,7 @@ #include <string.h> #include <unistd.h> +#include "utlist.h" #include "logger.h" #include "oic_malloc.h" #include "oic_string.h" @@ -39,20 +40,25 @@ extern "C" // declaration(s) for provisioning client using C-level provisioning API // user input definition for main loop on provisioning client -#define _10_DISCOV_ALL_DEVS_ 10 -#define _11_DISCOV_UNOWN_DEVS_ 11 -#define _12_DISCOV_OWN_DEVS_ 12 -#define _20_REGIST_DEVS_ 20 -#define _30_PROVIS_PAIR_DEVS_ 30 -#define _31_PROVIS_CRED_ 31 -#define _32_PROVIS_ACL_ 32 -#define _33_PROVIS_DP_ 33 -#define _34_CHECK_LINK_STATUS_ 34 -#define _40_UNLINK_PAIR_DEVS_ 40 -#define _50_REMOVE_SELEC_DEV_ 50 -#define _99_EXIT_PRVN_CLT_ 99 +#define _10_DISCOV_ALL_DEVS_ 10 +#define _11_DISCOV_UNOWN_DEVS_ 11 +#define _12_DISCOV_OWN_DEVS_ 12 +#define _20_REGIST_DEVS_ 20 +#define _30_PROVIS_PAIR_DEVS_ 30 +#define _31_PROVIS_CRED_ 31 +#define _32_PROVIS_ACL_ 32 +#define _33_PROVIS_DP_ 33 +#define _34_CHECK_LINK_STATUS_ 34 +#define _40_UNLINK_PAIR_DEVS_ 40 +#define _50_REMOVE_SELEC_DEV_ 50 +#define _51_REMOVE_DEV_WITH_UUID_ 51 +#define _52_RESET_SELEC_DEV_ 52 +#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 +155,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) @@ -191,6 +225,20 @@ static void removeDeviceCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool g_doneCB = true; } +static void syncDeviceCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError) +{ + if(!hasError) + { + OIC_LOG_V(INFO, TAG, "Sync Device SUCCEEDED - ctx: %s", (char*) ctx); + } + else + { + OIC_LOG_V(ERROR, TAG, "Sync Device FAILED - ctx: %s", (char*) ctx); + printResultList((const OCProvisionResult_t*) arr, nOfRes); + } + g_doneCB = true; +} + static void inputPinCB(char* pin, size_t len) { if(!pin || OXM_RANDOM_PIN_SIZE>=len) @@ -777,6 +825,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 @@ -877,6 +1044,97 @@ static int removeDevice(void) return 0; } +static int removeDeviceWithUuid(void) +{ + char strUuid[64] = {0}; + OicUuid_t revUuid; + printf("Input the UUID : "); + for(int ret=0; 1!=ret; ) + { + ret = scanf("%64s", strUuid); + for( ; 0x20<=getchar(); ); // for removing overflow garbages + // '0x20<=code' is character region + } + OCStackResult rst = ConvertStrToUuid(strUuid, &revUuid); + if(OC_STACK_OK != rst) + { + OIC_LOG_V(ERROR, TAG, "ConvertStrToUuid API error: %d", rst); + return -1; + } + + rst = OCRemoveDeviceWithUuid("RemoveDeviceWithUUID", DISCOVERY_TIMEOUT, &revUuid, removeDeviceCB); + if(OC_STACK_OK != rst) + { + OIC_LOG_V(ERROR, TAG, "OCRemoveDeviceWithUuid API error: %d", rst); + return -1; + } + + g_doneCB = false; + if(waitCallbackRet()) // input |g_doneCB| flag implicitly + { + OIC_LOG(ERROR, TAG, "OCRemoveDeviceWithUuid callback error"); + return -1; + } + + // display the removed result + printf(" > Removed %s Device\n", strUuid); + printf(" > Please Discover Owned Devices for the Registered Result, with [10|12] Menu\n"); + + return 0; +} + +static int resetDevice(void) +{ + // check |own_list| for removing device + if (!g_own_list || 1 > g_own_cnt) + { + printf(" > Owned Device List, to Reset Device, is Empty\n"); + printf(" > Please Register Unowned Devices first, with [20] Menu\n"); + return 0; + } + + // select device for removing it + int dev_num = 0; + for ( ; ; ) + { + printf(" > Enter Device Number, for Resetting Device: "); + 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"); + } + + g_doneCB = false; + printf(" Resetting Selected Owned Device..\n"); + + OCStackResult rst = OCResetDevice((void *) g_ctx, DISCOVERY_TIMEOUT, + getDevInst((const OCProvisionDev_t *) g_own_list, dev_num), syncDeviceCB); + if (OC_STACK_OK != rst) + { + OIC_LOG_V(ERROR, TAG, "OCResetDevice API error: %d", rst); + return -1; + } + + if (waitCallbackRet()) // input |g_doneCB| flag implicitly + { + OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error"); + return -1; + } + + // display the removed result + printf(" > Reset Selected Owned Device SUCCEEDED\n"); + printf(" > Please Discover Owned Devices for the Registered Result, with [10|12] Menu\n"); + + return 0; +} + static OicSecAcl_t* createAcl(const int dev_num) { if(0>=dev_num || g_own_cnt<dev_num) @@ -893,6 +1151,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 +1183,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,17 +1207,18 @@ 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) { - printf(" Enter Accessed Resource[%d] Name: ", i+1); + 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: (e.g. /a/led)", i+1); for(int ret=0; 1!=ret; ) { ret = scanf("%128s", rsrc_in); // '128' is ACL_RESRC_MAX_LEN @@ -960,14 +1226,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->href); + 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 (e.g. core.led): ", 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 for [%s]: ", rsrc->href); + 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 Interface[%d] Name (e.g. oic.if.baseline): ", 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 +1349,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 +1535,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; } @@ -1273,9 +1596,15 @@ static void printMenu(void) printf("** 40. Unlink Pairwise Things\n\n"); printf("** [E] REMOVE THE SELECTED DEVICE\n"); - printf("** 50. Remove the Selected Device\n\n"); + printf("** 50. Remove the Selected Device\n"); + printf("** 51. Remove Device with UUID (UUID input is required)\n"); + printf("** 52. Reset the Selected Device\n\n"); - printf("** [F] EXIT PROVISIONING CLIENT\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("** [G] EXIT PROVISIONING CLIENT\n"); printf("** 99. Exit Provisionong Client\n\n"); printf("************************************************************\n\n"); @@ -1393,6 +1722,30 @@ int main() OIC_LOG(ERROR, TAG, "_50_REMOVE_SELEC_DEV_: error"); } break; + case _51_REMOVE_DEV_WITH_UUID_: + if(removeDeviceWithUuid()) + { + OIC_LOG(ERROR, TAG, "_51_REMOVE_DEV_WITH_UUID_: error"); + } + break; + case _52_RESET_SELEC_DEV_: + if(resetDevice()) + { + OIC_LOG(ERROR, TAG, "_52_RESET_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: diff --git a/resource/csdk/security/provisioning/src/credentialgenerator.c b/resource/csdk/security/provisioning/src/credentialgenerator.c index 44e80a42e..50623748c 100644 --- a/resource/csdk/security/provisioning/src/credentialgenerator.c +++ b/resource/csdk/security/provisioning/src/credentialgenerator.c @@ -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; } diff --git a/resource/csdk/security/provisioning/src/ocprovisioningmanager.c b/resource/csdk/security/provisioning/src/ocprovisioningmanager.c index b5d4bed56..1fb938863 100644 --- a/resource/csdk/security/provisioning/src/ocprovisioningmanager.c +++ b/resource/csdk/security/provisioning/src/ocprovisioningmanager.c @@ -22,6 +22,7 @@ #include <string.h> #include "ocprovisioningmanager.h" #include "pmutility.h" +#include "srmutility.h" #include "ownershiptransfermanager.h" #include "oic_malloc.h" #include "logger.h" @@ -163,6 +164,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. @@ -274,6 +305,51 @@ error: return res; } +static OCStackResult RemoveDeviceInfoFromLocal(const OCProvisionDev_t* pTargetDev) +{ + // Remove credential of revoked device from SVR database + OCStackResult res = OC_STACK_ERROR; + const OicSecCred_t *cred = NULL; + cred = GetCredResourceData(&pTargetDev->doxm->deviceID); + if (cred == NULL) + { + OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to get credential of remove device."); + goto error; + } + + res = RemoveCredential(&cred->subject); + if (res != OC_STACK_RESOURCE_DELETED) + { + OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to remove credential."); + goto error; + } + + /** + * Change the device status as stale status. + * If all request are successed, this device information will be deleted. + */ + res = PDMSetDeviceStale(&pTargetDev->doxm->deviceID); + if (res != OC_STACK_OK) + { + OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to set device status as stale"); + goto error; + } + + // TODO: We need to add new mechanism to clean up the stale state of the device. + + //Close the DTLS session of the removed device. + CAEndpoint_t* endpoint = (CAEndpoint_t *)&pTargetDev->endpoint; + endpoint->port = pTargetDev->securePort; + CAResult_t caResult = CACloseDtlsSession(endpoint); + if(CA_STATUS_OK != caResult) + { + OIC_LOG_V(WARNING, TAG, "OCRemoveDevice : Failed to close DTLS session : %d", caResult); + } + +error: + return res; +} + /* * Function to device revocation * This function will remove credential of target device from all devices in subnet. @@ -319,65 +395,189 @@ OCStackResult OCRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDis } } - // Remove credential of revoked device from SVR database - const OicSecCred_t *cred = NULL; - cred = GetCredResourceData(&pTargetDev->doxm->deviceID); - if (cred == NULL) + res = RemoveDeviceInfoFromLocal(pTargetDev); + if(OC_STACK_OK != res) { - OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to get credential of remove device."); + OIC_LOG(ERROR, TAG, "Filed to remove the device information from local."); goto error; } - res = RemoveCredential(&cred->subject); - if (res != OC_STACK_RESOURCE_DELETED) + if(OC_STACK_CONTINUE == resReq) { - OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to remove credential."); + /** + * If there is no linked device, PM does not send any request. + * So we should directly invoke the result callback to inform the result of OCRemoveDevice. + */ + if(resultCallback) + { + resultCallback(ctx, 0, NULL, false); + } + res = OC_STACK_OK; + } + +error: + OIC_LOG(INFO, TAG, "OUT OCRemoveDevice"); + return res; +} + +/* +* Function to device revocation +* This function will remove credential of target device from all devices in subnet. +* +* @param[in] ctx Application context would be returned in result callback +* @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds) +* @param[in] pTargetDev Device information to be revoked. +* @param[in] resultCallback callback provided by API user, callback will be called when +* credential revocation is finished. + * @return OC_STACK_OK in case of success and other value otherwise. +*/ +OCStackResult OCRemoveDeviceWithUuid(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery, + const OicUuid_t* pTargetUuid, + OCProvisionResultCB resultCallback) +{ + OIC_LOG(INFO, TAG, "IN OCRemoveDeviceWithUuid"); + OCStackResult res = OC_STACK_ERROR; + if (!pTargetUuid || 0 == waitTimeForOwnedDeviceDiscovery) + { + OIC_LOG(INFO, TAG, "OCRemoveDeviceWithUuid : Invalied parameters"); + return OC_STACK_INVALID_PARAM; + } + if (!resultCallback) + { + OIC_LOG(INFO, TAG, "OCRemoveDeviceWithUuid : NULL Callback"); + return OC_STACK_INVALID_CALLBACK; + } + + OCProvisionDev_t* pOwnedDevList = NULL; + //2. Find owned device from the network + res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList); + if (OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "OCRemoveDeviceWithUuid : Failed to PMDeviceDiscovery"); goto error; } - /** - * Change the device status as stale status. - * If all request are successed, this device information will be deleted. - */ - res = PDMSetDeviceStale(&pTargetDev->doxm->deviceID); - if (res != OC_STACK_OK) + OCProvisionDev_t* pTargetDev = NULL; + LL_FOREACH(pOwnedDevList, pTargetDev) { - OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to set device status as stale"); + if(memcmp(&pTargetDev->doxm->deviceID.id, pTargetUuid->id, sizeof(pTargetUuid->id)) == 0) + { + break; + } + } + + char* strUuid = NULL; + if(OC_STACK_OK != ConvertUuidToStr(pTargetUuid, &strUuid)) + { + OIC_LOG(WARNING, TAG, "Failed to covert UUID to String."); goto error; } - // TODO: We need to add new mechanism to clean up the stale state of the device. + if(pTargetDev) + { + OIC_LOG_V(INFO, TAG, "[%s] is dectected on the network.", strUuid); + OIC_LOG_V(INFO, TAG, "Trying [%s] revocation.", strUuid); - res = resReq; + // Send DELETE requests to linked devices + OCStackResult resReq = OC_STACK_ERROR; // Check that we have to wait callback or not. + resReq = SRPRemoveDeviceWithoutDiscovery(ctx, pOwnedDevList, pTargetDev, resultCallback); + if (OC_STACK_OK != resReq) + { + if (OC_STACK_CONTINUE == resReq) + { + OIC_LOG(DEBUG, TAG, "OCRemoveDeviceWithUuid : Revoked device has no linked device except PT."); + } + else + { + OIC_LOG(ERROR, TAG, "OCRemoveDeviceWithUuid : Failed to invoke SRPRemoveDevice"); + res = resReq; + OICFree(strUuid); + goto error; + } + } - //Close the DTLS session of the removed device. - CAEndpoint_t* endpoint = (CAEndpoint_t *)&pTargetDev->endpoint; - endpoint->port = pTargetDev->securePort; - CAResult_t caResult = CACloseDtlsSession(endpoint); - if(CA_STATUS_OK != caResult) + res = RemoveDeviceInfoFromLocal(pTargetDev); + if(OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "OCRemoveDeviceWithUuid : Filed to remove the device information from local."); + OICFree(strUuid); + goto error; + } + + if(OC_STACK_CONTINUE == resReq) + { + /** + * If there is no linked device, PM does not send any request. + * So we should directly invoke the result callback to inform the result of OCRemoveDevice. + */ + if(resultCallback) + { + resultCallback(ctx, 0, NULL, false); + } + res = OC_STACK_OK; + } + } + else { - OIC_LOG_V(WARNING, TAG, "OCRemoveDevice : Failed to close DTLS session : %d", caResult); + OIC_LOG_V(WARNING, TAG, "OCRemoveDeviceWithUuid : Failed to find the [%s] on the network.", strUuid); + res = OC_STACK_ERROR; } - /** - * If there is no linked device, PM does not send any request. - * So we should directly invoke the result callback to inform the result of OCRemoveDevice. - */ - if(OC_STACK_CONTINUE == res) +error: + OICFree(strUuid); + PMDeleteDeviceList(pOwnedDevList); + OIC_LOG(INFO, TAG, "OUT OCRemoveDeviceWithUuid"); + return res; +} + +/* + * Function to reset the target device. + * This function will remove credential and ACL of target device from all devices in subnet. + * + * @param[in] ctx Application context would be returned in result callback + * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds) + * @param[in] pTargetDev Device information to be revoked. + * @param[in] resultCallback callback provided by API user, callback will be called when + * credential revocation is finished. + * @return OC_STACK_OK in case of success and other value otherwise. + */ +OCStackResult OCResetDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery, + const OCProvisionDev_t* pTargetDev, + OCProvisionResultCB resultCallback) +{ + OIC_LOG(INFO, TAG, "IN OCResetDevice"); + OCStackResult res = OC_STACK_ERROR; + if (!pTargetDev || 0 == waitTimeForOwnedDeviceDiscovery) + { + OIC_LOG(INFO, TAG, "OCResetDevice : Invalid parameters"); + return OC_STACK_INVALID_PARAM; + } + if (!resultCallback) { + OIC_LOG(INFO, TAG, "OCResetDevice : NULL Callback"); + return OC_STACK_INVALID_CALLBACK; + } + + // Send DELETE requests to linked devices + res = SRPSyncDevice(ctx, waitTimeForOwnedDeviceDiscovery, pTargetDev, resultCallback); + if (OC_STACK_CONTINUE == res) + { + OIC_LOG(DEBUG, TAG, "OCResetDevice : Target device has no linked device except PT."); if(resultCallback) { resultCallback(ctx, 0, NULL, false); } + SRPResetDevice(pTargetDev, resultCallback); res = OC_STACK_OK; } - -error: - OIC_LOG(INFO, TAG, "OUT OCRemoveDevice"); + else if(OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to invoke SRPSyncDevice"); + } + OIC_LOG(INFO, TAG, "OUT OCResetDevice"); return res; } - /** * Internal Function to update result in link result array. */ diff --git a/resource/csdk/security/provisioning/src/ownershiptransfermanager.c b/resource/csdk/security/provisioning/src/ownershiptransfermanager.c index 7b22d469e..3afff636a 100644 --- a/resource/csdk/security/provisioning/src/ownershiptransfermanager.c +++ b/resource/csdk/security/provisioning/src/ownershiptransfermanager.c @@ -136,7 +136,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 PosttOwnerTransferModeToResource(OTMContext_t* otmCtx); /** * Function to send request to resource to get its pstat resource information. @@ -154,7 +154,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 +163,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 +172,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 +181,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 +191,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 +201,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 +315,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 +419,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) { @@ -455,7 +477,7 @@ static OCStackApplicationResult OwnerTransferModeHandler(void *ctx, OCDoHandle U OTMContext_t* otmCtx = (OTMContext_t*)ctx; (void)UNUSED; - if(clientResponse->result == OC_STACK_OK) + if(clientResponse->result == OC_STACK_RESOURCE_CHANGED) { OIC_LOG(INFO, TAG, "OwnerTransferModeHandler : response result = OC_STACK_OK"); //Send request : GET /oic/sec/pstat @@ -535,8 +557,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."); @@ -575,7 +597,7 @@ static OCStackApplicationResult OwnerUuidUpdateHandler(void *ctx, OCDoHandle UNU OCStackResult res = OC_STACK_OK; OTMContext_t* otmCtx = (OTMContext_t*)ctx; - if(OC_STACK_OK == clientResponse->result) + if(OC_STACK_RESOURCE_CHANGED == clientResponse->result) { if(otmCtx && otmCtx->selectedDeviceInfo) { @@ -587,12 +609,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; } @@ -630,7 +652,7 @@ static OCStackApplicationResult OperationModeUpdateHandler(void *ctx, OCDoHandle OTMContext_t* otmCtx = (OTMContext_t*)ctx; (void) UNUSED; - if (OC_STACK_OK == clientResponse->result) + if (OC_STACK_RESOURCE_CHANGED == clientResponse->result) { OCStackResult res = OC_STACK_ERROR; OicSecOxm_t selOxm = otmCtx->selectedDeviceInfo->doxm->oxmSel; @@ -694,7 +716,7 @@ static OCStackApplicationResult OwnerCredentialHandler(void *ctx, OCDoHandle UNU OCStackResult res = OC_STACK_OK; OTMContext_t* otmCtx = (OTMContext_t*)ctx; - if(OC_STACK_RESOURCE_CREATED == clientResponse->result) + if(OC_STACK_RESOURCE_CHANGED == clientResponse->result) { if(otmCtx && otmCtx->selectedDeviceInfo) { @@ -738,11 +760,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; } @@ -782,14 +804,14 @@ static OCStackApplicationResult OwnershipInformationHandler(void *ctx, OCDoHandl OCStackResult res = OC_STACK_OK; OTMContext_t* otmCtx = (OTMContext_t*)ctx; - if(OC_STACK_OK == clientResponse->result) + if(OC_STACK_RESOURCE_CHANGED == clientResponse->result) { if(otmCtx && otmCtx->selectedDeviceInfo) { 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"); @@ -831,13 +853,13 @@ static OCStackApplicationResult ProvisioningStatusHandler(void *ctx, OCDoHandle (void)UNUSED; OCStackResult res = OC_STACK_OK; - if(OC_STACK_OK == clientResponse->result) + if(OC_STACK_RESOURCE_CHANGED == clientResponse->result) { if(otmCtx && otmCtx->selectedDeviceInfo) { 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"); @@ -877,7 +899,7 @@ static OCStackApplicationResult ReadyForNomalStatusHandler(void *ctx, OCDoHandle OTMContext_t* otmCtx = (OTMContext_t*) ctx; (void)UNUSED; - if (OC_STACK_OK == clientResponse->result) + if (OC_STACK_RESOURCE_CHANGED == clientResponse->result) { OIC_LOG(INFO, TAG, "Device state is in Ready for Normal Operation."); OCStackResult res = PDMAddDevice(&otmCtx->selectedDeviceInfo->doxm->deviceID); @@ -904,9 +926,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 +944,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 +975,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 +998,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 +1012,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 +1036,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 +1060,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 +1100,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 +1111,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 +1128,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 +1156,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 +1185,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); @@ -1178,7 +1202,7 @@ static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx) secPayload->base.type = PAYLOAD_TYPE_SECURITY; OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, - &secPayload->securityData, &secPayload->payloadSize); + &secPayload->securityData, &secPayload->payloadSize, true); if (OC_STACK_OK != res && NULL == secPayload->securityData) { OCPayloadDestroy((OCPayload *)secPayload); @@ -1191,21 +1215,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 +1243,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); @@ -1232,7 +1256,7 @@ static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx) } secPayload->base.type = PAYLOAD_TYPE_SECURITY; OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData, - &secPayload->payloadSize); + &secPayload->payloadSize, true); if (OC_STACK_OK != res) { OCPayloadDestroy((OCPayload *)secPayload); @@ -1244,14 +1268,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 +1298,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"); @@ -1380,9 +1404,31 @@ OCStackResult OTMDoOwnershipTransfer(void* ctx, } if (isDuplicate) { - OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Device ID is duplicated"); - res = OC_STACK_INVALID_PARAM; - goto error; + bool isStale = false; + res = PDMIsDeviceStale(&pCurDev->doxm->deviceID, &isStale); + if(OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "Internal error in PDMIsDeviceStale"); + goto error; + } + if(isStale) + { + OIC_LOG(INFO, TAG, "Detected duplicated UUID in stale status, "\ + "this UUID will be removed from PDM"); + + res = PDMDeleteDevice(&pCurDev->doxm->deviceID); + if(OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "Internal error in PDMDeleteDevice"); + goto error; + } + } + else + { + OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Device UUID is duplicated"); + res = OC_STACK_INVALID_PARAM; + goto error; + } } memcpy(otmCtx->ctxResultArray[devIdx].deviceId.id, pCurDev->doxm->deviceID.id, @@ -1402,9 +1448,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) { @@ -1423,7 +1469,7 @@ OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx) } secPayload->base.type = PAYLOAD_TYPE_SECURITY; if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat, - &secPayload->securityData, &secPayload->payloadSize)) + &secPayload->securityData, &secPayload->payloadSize, true)) { OCPayloadDestroy((OCPayload *)secPayload); return OC_STACK_INVALID_JSON; @@ -1438,7 +1484,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 +1493,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 +1501,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) { @@ -1481,7 +1527,7 @@ OCStackResult PutNormalOperationStatus(OTMContext_t* otmCtx) } secPayload->base.type = PAYLOAD_TYPE_SECURITY; if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat, - &secPayload->securityData, &secPayload->payloadSize)) + &secPayload->securityData, &secPayload->payloadSize, true)) { OCPayloadDestroy((OCPayload *)secPayload); return OC_STACK_INVALID_JSON; @@ -1496,7 +1542,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 +1551,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 +1559,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; } diff --git a/resource/csdk/security/provisioning/src/oxmjustworks.c b/resource/csdk/security/provisioning/src/oxmjustworks.c index a0f1e96aa..d8518ff62 100644 --- a/resource/csdk/security/provisioning/src/oxmjustworks.c +++ b/resource/csdk/security/provisioning/src/oxmjustworks.c @@ -43,7 +43,7 @@ OCStackResult CreateJustWorksSelectOxmPayload(OTMContext_t *otmCtx, uint8_t **pa *payload = NULL; *size = 0; - return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size); + return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size, true); } OCStackResult CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx, uint8_t **payload, size_t *size) @@ -65,7 +65,7 @@ OCStackResult CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx, uint8_t *payload = NULL; *size = 0; - return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size); + return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size, true); } OCStackResult LoadSecretJustWorksCallback(OTMContext_t* UNUSED_PARAM) diff --git a/resource/csdk/security/provisioning/src/oxmrandompin.c b/resource/csdk/security/provisioning/src/oxmrandompin.c index 4efc23884..d1cb7f522 100644 --- a/resource/csdk/security/provisioning/src/oxmrandompin.c +++ b/resource/csdk/security/provisioning/src/oxmrandompin.c @@ -47,7 +47,7 @@ OCStackResult CreatePinBasedSelectOxmPayload(OTMContext_t* otmCtx, uint8_t **pay otmCtx->selectedDeviceInfo->doxm->oxmSel = OIC_RANDOM_DEVICE_PIN; - return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size); + return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size, true); } OCStackResult CreatePinBasedOwnerTransferPayload(OTMContext_t* otmCtx, uint8_t **payload, size_t *size) @@ -68,7 +68,7 @@ OCStackResult CreatePinBasedOwnerTransferPayload(OTMContext_t* otmCtx, uint8_t * } memcpy(otmCtx->selectedDeviceInfo->doxm->owner.id, uuidPT.id , UUID_LENGTH); - return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size); + return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size, true); } OCStackResult InputPinCodeCallback(OTMContext_t *otmCtx) diff --git a/resource/csdk/security/provisioning/src/pmutility.c b/resource/csdk/security/provisioning/src/pmutility.c index e55e9a69e..56bf9b240 100644 --- a/resource/csdk/security/provisioning/src/pmutility.c +++ b/resource/csdk/security/provisioning/src/pmutility.c @@ -584,6 +584,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 +710,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 +803,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 +817,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 +845,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 +862,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 +905,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"); diff --git a/resource/csdk/security/provisioning/src/provisioningdatabasemanager.c b/resource/csdk/security/provisioning/src/provisioningdatabasemanager.c index 80b3eb228..1796ab0d4 100644 --- a/resource/csdk/security/provisioning/src/provisioningdatabasemanager.c +++ b/resource/csdk/security/provisioning/src/provisioningdatabasemanager.c @@ -227,7 +227,7 @@ OCStackResult PDMAddDevice(const OicUuid_t *UUID) /** * Function to check whether device is stale or not */ -static OCStackResult isDeviceStale(const OicUuid_t *uuid, bool *result) +OCStackResult PDMIsDeviceStale(const OicUuid_t *uuid, bool *result) { if (NULL == uuid || NULL == result) { @@ -359,7 +359,7 @@ OCStackResult PDMLinkDevices(const OicUuid_t *UUID1, const OicUuid_t *UUID2) } bool result = false; - if (OC_STACK_OK != isDeviceStale(UUID1, &result)) + if (OC_STACK_OK != PDMIsDeviceStale(UUID1, &result)) { OIC_LOG(ERROR, TAG, "Internal error occured"); return OC_STACK_ERROR; @@ -370,7 +370,7 @@ OCStackResult PDMLinkDevices(const OicUuid_t *UUID1, const OicUuid_t *UUID2) return OC_STACK_INVALID_PARAM; } result = false; - if (OC_STACK_OK != isDeviceStale(UUID2, &result)) + if (OC_STACK_OK != PDMIsDeviceStale(UUID2, &result)) { OIC_LOG(ERROR, TAG, "Internal error occured"); return OC_STACK_ERROR; @@ -636,7 +636,7 @@ OCStackResult PDMGetLinkedDevices(const OicUuid_t *UUID, OCUuidList_t **UUIDLIST return OC_STACK_INVALID_PARAM; } bool result = false; - OCStackResult ret = isDeviceStale(UUID, &result); + OCStackResult ret = PDMIsDeviceStale(UUID, &result); if (OC_STACK_OK != ret) { OIC_LOG(ERROR, TAG, "Internal error occured"); @@ -802,7 +802,7 @@ OCStackResult PDMIsLinkExists(const OicUuid_t* uuidOfDevice1, const OicUuid_t* u } bool isStale = false; - if (OC_STACK_OK != isDeviceStale(uuidOfDevice1, &isStale)) + if (OC_STACK_OK != PDMIsDeviceStale(uuidOfDevice1, &isStale)) { OIC_LOG(ERROR, TAG, "uuidOfDevice1:Internal error occured"); return OC_STACK_ERROR; @@ -814,7 +814,7 @@ OCStackResult PDMIsLinkExists(const OicUuid_t* uuidOfDevice1, const OicUuid_t* u } isStale = false; - if (OC_STACK_OK != isDeviceStale(uuidOfDevice2, &isStale)) + if (OC_STACK_OK != PDMIsDeviceStale(uuidOfDevice2, &isStale)) { OIC_LOG(ERROR, TAG, "uuidOfDevice2:Internal error occured"); return OC_STACK_ERROR; diff --git a/resource/csdk/security/provisioning/src/secureresourceprovider.c b/resource/csdk/security/provisioning/src/secureresourceprovider.c index 9799ea450..d9054d4dc 100644 --- a/resource/csdk/security/provisioning/src/secureresourceprovider.c +++ b/resource/csdk/security/provisioning/src/secureresourceprovider.c @@ -91,6 +91,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. */ @@ -187,9 +197,9 @@ static OCStackApplicationResult provisionCredentialCB2(void *ctx, OCDoHandle UNU OIC_LOG(INFO, TAG, "provisionCredentialCB2 called"); if (clientResponse) { - if(OC_STACK_RESOURCE_CREATED == clientResponse->result) + if(OC_STACK_RESOURCE_CHANGED == clientResponse->result) { - registerResultForCredProvisioning(credData, OC_STACK_RESOURCE_CREATED, 2); + registerResultForCredProvisioning(credData, OC_STACK_RESOURCE_CHANGED, 2); OCStackResult res = PDMLinkDevices(&credData->deviceInfo1->doxm->deviceID, &credData->deviceInfo2->doxm->deviceID); if (OC_STACK_OK != res) @@ -239,10 +249,10 @@ static OCStackApplicationResult provisionCredentialCB1(void *ctx, OCDoHandle UNU const OCProvisionResultCB resultCallback = credData->resultCallback; if (clientResponse) { - if (OC_STACK_RESOURCE_CREATED == clientResponse->result) + if (OC_STACK_RESOURCE_CHANGED == clientResponse->result) { // send credentials to second device - registerResultForCredProvisioning(credData, OC_STACK_RESOURCE_CREATED,1); + registerResultForCredProvisioning(credData, OC_STACK_RESOURCE_CHANGED,1); OCStackResult res = provisionCredentials(credInfo, deviceInfo, credData, provisionCredentialCB2); DeleteCredList(credInfo); @@ -304,7 +314,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); @@ -421,9 +433,9 @@ static OCStackApplicationResult SRPProvisionCRLCB(void *ctx, OCDoHandle UNUSED, if (clientResponse) { - if(OC_STACK_RESOURCE_CREATED == clientResponse->result) + if(OC_STACK_RESOURCE_CHANGED == clientResponse->result) { - registerResultForCRLProvisioning(crlData, OC_STACK_RESOURCE_CREATED); + registerResultForCRLProvisioning(crlData, OC_STACK_RESOURCE_CHANGED); ((OCProvisionResultCB)(resultCallback))(crlData->ctx, crlData->numOfResults, crlData->resArr, false); @@ -541,8 +553,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)) { @@ -604,9 +617,9 @@ static OCStackApplicationResult provisionCertCB(void *ctx, OCDoHandle UNUSED, OIC_LOG(INFO, TAG, "provisionCertCred called"); if (clientResponse) { - if(OC_STACK_RESOURCE_CREATED == clientResponse->result) + if(OC_STACK_RESOURCE_CHANGED == clientResponse->result) { - registerResultForCertProvisioning(certData, OC_STACK_RESOURCE_CREATED); + registerResultForCertProvisioning(certData, OC_STACK_RESOURCE_CHANGED); ((OCProvisionResultCB)(resultCallback))(certData->ctx, certData->numOfResults, certData->resArr, false); @@ -824,9 +837,9 @@ static OCStackApplicationResult SRPProvisionACLCB(void *ctx, OCDoHandle UNUSED, if (clientResponse) { - if(OC_STACK_RESOURCE_CREATED == clientResponse->result) + if(OC_STACK_RESOURCE_CHANGED == clientResponse->result) { - registerResultForACLProvisioning(aclData, OC_STACK_RESOURCE_CREATED); + registerResultForACLProvisioning(aclData, OC_STACK_RESOURCE_CHANGED); ((OCProvisionResultCB)(resultCallback))(aclData->ctx, aclData->numOfResults, aclData->resArr, false); @@ -865,6 +878,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, @@ -951,7 +967,7 @@ static OCStackApplicationResult SRPProvisionDirectPairingCB(void *ctx, OCDoHandl if (clientResponse) { - if(OC_STACK_RESOURCE_CREATED == clientResponse->result) + if(OC_STACK_RESOURCE_CHANGED == clientResponse->result) { registerResultForDirectPairingProvisioning(pconfData, OC_STACK_OK); ((OCProvisionResultCB)(resultCallback))(pconfData->ctx, pconfData->numOfResults, @@ -1055,7 +1071,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); @@ -1159,6 +1175,64 @@ static OCStackResult SendDeleteCredentialRequest(void* ctx, return ret; } +static OCStackResult SendDeleteACLRequest(void* ctx, + OCClientResponseHandler respHandler, + const OCProvisionDev_t* revokedDev, + const OCProvisionDev_t* destDev) +{ + OIC_LOG(DEBUG, TAG, "IN SendDeleteACLRequest"); + + if (NULL == ctx || NULL == respHandler || NULL == revokedDev || NULL == destDev) + { + return OC_STACK_INVALID_PARAM; + } + + char *subID = NULL; + OCStackResult ret = ConvertUuidToStr(&revokedDev->doxm->deviceID, &subID); + if(OC_STACK_OK != ret) + { + OIC_LOG(ERROR, TAG, "SendDeleteACLRequest : Failed to canonical UUID encoding"); + return OC_STACK_ERROR; + } + + char reqBuf[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0}; + int snRet = 0; + //coaps://0.0.0.0:5684/oic/sec/acl?subjectuuid=(Canonical ENCODED UUID) + snRet = snprintf(reqBuf, sizeof(reqBuf), SRP_FORM_DELETE_CREDENTIAL, destDev->endpoint.addr, + destDev->securePort, OIC_RSRC_ACL_URI, OIC_JSON_SUBJECTID_NAME, subID); + OICFree(subID); + if (snRet < 0) + { + OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Error (snprintf) %d\n", snRet); + return OC_STACK_ERROR; + } + else if ((size_t)snRet >= sizeof(reqBuf)) + { + OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Truncated (snprintf) %d\n", snRet); + return OC_STACK_ERROR; + } + + OCCallbackData cbData; + memset(&cbData, 0, sizeof(cbData)); + cbData.context = ctx; + cbData.cb = respHandler; + cbData.cd = NULL; + OIC_LOG_V(INFO, TAG, "URI: %s",reqBuf); + + OIC_LOG(DEBUG, TAG, "Sending remove ACL request to resource server"); + + ret = OCDoResource(NULL, OC_REST_DELETE, reqBuf, + &destDev->endpoint, NULL, + CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0); + if (OC_STACK_OK != ret) + { + OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Error in OCDoResource %d", ret); + } + OIC_LOG(DEBUG, TAG, "OUT SendDeleteACLRequest"); + + return ret; +} + /** * Callback handler of unlink second device. * @@ -1432,6 +1506,34 @@ static void registerResultForRemoveDevice(RemoveData_t *removeData, OicUuid_t *p } } +static void registerResultForResetDevice(RemoveData_t *removeData, OicUuid_t *pLinkedDevId, + OCStackResult stackresult, bool hasError) +{ + OIC_LOG_V(INFO, TAG, "Inside registerResultForResetDevice removeData->numOfResults is %zu\n", + removeData->numOfResults + 1); + if (pLinkedDevId) + { + memcpy(removeData->removeRes[(removeData->numOfResults)].deviceId.id, + &pLinkedDevId->id, sizeof(pLinkedDevId->id)); + } + else + { + memset(removeData->removeRes[(removeData->numOfResults)].deviceId.id, + 0, sizeof(pLinkedDevId->id) ); + } + removeData->removeRes[(removeData->numOfResults)].res = stackresult; + removeData->hasError = hasError; + ++(removeData->numOfResults); + + // If we get suffcient result from linked devices, we have to call user callback and do free + if (removeData->sizeOfResArray == removeData->numOfResults) + { + removeData->resultCallback(removeData->ctx, removeData->numOfResults, removeData->removeRes, + removeData->hasError); + DeleteRemoveData_t(removeData); + } +} + /** * Callback handler of unlink first device. * @@ -1511,6 +1613,171 @@ static OCStackApplicationResult SRPRemoveDeviceCB(void *delDevCtx, OCDoHandle ha return OC_STACK_DELETE_TRANSACTION; } +/** + * Callback handler of reset device. + * + * @param[in] ctx ctx value passed to callback from calling function. + * @param[in] handle 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 SRPSyncDeviceCredCB(void *delDevCtx, OCDoHandle handle, + OCClientResponse *clientResponse) +{ + //Update the delete credential into delete device context + //Save the deleted status in delDevCtx + (void)handle; + OIC_LOG_V(INFO, TAG, "Inside SRPSyncDeviceCredCB."); + VERIFY_NON_NULL(TAG, delDevCtx, ERROR, OC_STACK_DELETE_TRANSACTION); + OCStackResult res = OC_STACK_ERROR; + + RemoveData_t* removeData = (RemoveData_t*)delDevCtx; + OCProvisionDev_t * pTargetDev = PMCloneOCProvisionDev(removeData->revokeTargetDev); + OCProvisionResultCB resultCallback = removeData->resultCallback; + if (clientResponse) + { + OicUuid_t revDevUuid = {.id={0}}; + if(UUID_LENGTH == clientResponse->identity.id_length) + { + memcpy(revDevUuid.id, clientResponse->identity.id, sizeof(revDevUuid.id)); + if (OC_STACK_RESOURCE_DELETED == clientResponse->result) + { + res = PDMUnlinkDevices(&removeData->revokeTargetDev->doxm->deviceID, &revDevUuid); + if (OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one."); + registerResultForResetDevice(removeData, &revDevUuid, + OC_STACK_INCONSISTENT_DB, true); + + return OC_STACK_DELETE_TRANSACTION; + } + + registerResultForResetDevice(removeData, &revDevUuid, + OC_STACK_RESOURCE_DELETED, false); + } + else + { + registerResultForResetDevice(removeData, &revDevUuid, + clientResponse->result, false); + OIC_LOG(ERROR, TAG, "Unexpected result from DELETE credential request!"); + } + } + else + { + OIC_LOG_V(WARNING, TAG, "Incorrect length of device UUID was sent from %s:%d", + clientResponse->devAddr.addr, clientResponse->devAddr.port); + + if (OC_STACK_RESOURCE_DELETED == clientResponse->result) + { + /** + * Since server's credential was deleted, + * register result as OC_STACK_INCONSISTENT_DB with NULL UUID. + */ + OIC_LOG_V(ERROR, TAG, "But server's credential was deleted."); + registerResultForResetDevice(removeData, NULL, OC_STACK_INCONSISTENT_DB, true); + } + else + { + registerResultForResetDevice(removeData, NULL, clientResponse->result, true); + } + } + } + else + { + registerResultForResetDevice(removeData, NULL, OC_STACK_ERROR, true); + OIC_LOG(ERROR, TAG, "SRPSyncDevice received Null clientResponse"); + } + + SRPResetDevice(pTargetDev, resultCallback); + + return OC_STACK_DELETE_TRANSACTION; +} + +/** + * Callback handler of reset device sync-up + * + * @param[in] ctx ctx value passed to callback from calling function. + * @param[in] handle 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 SRPSyncDeviceACLCB(void *ctx, OCDoHandle handle, + OCClientResponse *clientResponse) +{ + return OC_STACK_DELETE_TRANSACTION; +} + +/** + * Callback handler of device remote reset. + * + * @param[in] ctx ctx value passed to callback from calling function. + * @param[in] handle 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 SRPResetDeviceCB(void *ctx, OCDoHandle handle, + OCClientResponse *clientResponse) +{ + OIC_LOG(DEBUG, TAG, "IN SRPResetDeviceCB"); + if(OC_STACK_OK == clientResponse->result) + { + OIC_LOG(DEBUG, TAG, "Change Target Device Pstat Cm SUCCEEDED"); + } + + // Delete Cred and ACL related to the target device. + const OicSecCred_t *cred = NULL; + OCProvisionDev_t * pTargetDev = (OCProvisionDev_t *)ctx; + cred = GetCredResourceData(&pTargetDev->doxm->deviceID); + if (cred == NULL) + { + OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to get credential of target device."); + goto error; + } + + OCStackResult res = RemoveCredential(&cred->subject); + if (res != OC_STACK_RESOURCE_DELETED && res != OC_STACK_NO_RESOURCE) + { + OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to remove credential."); + goto error; + } + + res = RemoveACE(&cred->subject, NULL); + if (res != OC_STACK_RESOURCE_DELETED && res != OC_STACK_NO_RESOURCE) + { + OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to remove ACL."); + goto error; + } + if (OC_STACK_OK != PDMDeleteDevice(&pTargetDev->doxm->deviceID)) + { + OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to delete device from PDM"); + } + + //Close the DTLS session of the reset device. + CAEndpoint_t* endpoint = (CAEndpoint_t *)&clientResponse->devAddr; + CAResult_t caResult = CACloseDtlsSession(endpoint); + if(CA_STATUS_OK != caResult) + { + OIC_LOG_V(WARNING, TAG, "OCResetDevice : Failed to close DTLS session : %d", caResult); + } + + /** + * If there is no linked device, PM does not send any request. + * So we should directly invoke the result callback to inform the result of OCResetDevice. + */ + if(OC_STACK_NO_RESOURCE == res) + { + res = OC_STACK_OK; + } + +error: + OICFree(pTargetDev); + return OC_STACK_DELETE_TRANSACTION; + +} + static OCStackResult GetListofDevToReqDeleteCred(const OCProvisionDev_t* pRevokeTargetDev, OCProvisionDev_t* pOwnedDevList, OCUuidList_t* pLinkedUuidList, @@ -1709,3 +1976,646 @@ error: OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDevice"); return res; } + +/* +* Function to device revocation +* This function will remove credential of target device from all devices in subnet. +* +* @param[in] ctx Application context would be returned in result callback +* @param[in] pOwnedDevList List of owned devices +* @param[in] pTargetDev Device information to be revoked. +* @param[in] resultCallback callback provided by API user, callback will be called when +* credential revocation is finished. +* @return OC_STACK_OK in case of success and other value otherwise. +* If OC_STACK_OK is returned, the caller of this API should wait for callback. +* OC_STACK_CONTINUE means operation is success but no request is need to be initiated. +*/ +OCStackResult SRPRemoveDeviceWithoutDiscovery(void* ctx, const OCProvisionDev_t* pOwnedDevList, + const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback) +{ + OIC_LOG(INFO, TAG, "IN SRPRemoveDeviceWithoutDiscovery"); + + if (!pTargetDev || !pOwnedDevList) + { + OIC_LOG(INFO, TAG, "SRPRemoveDeviceWithoutDiscovery : NULL parameters"); + return OC_STACK_INVALID_PARAM; + } + if (!resultCallback) + { + OIC_LOG(INFO, TAG, "SRPRemoveDeviceWithoutDiscovery : NULL Callback"); + return OC_STACK_INVALID_CALLBACK; + } + + // Declare variables in here to handle error cases with goto statement. + OCProvisionDev_t* pLinkedDevList = NULL; + RemoveData_t* removeData = NULL; + + //1. Find all devices that has a credential of the revoked device + OCUuidList_t* pLinkedUuidList = NULL; + size_t numOfDevices = 0; + OCStackResult res = OC_STACK_ERROR; + res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices); + if (OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to get linked devices information"); + return res; + } + // if there is no related device, we can skip further process. + if (0 == numOfDevices) + { + OIC_LOG(DEBUG, TAG, "SRPRemoveDeviceWithoutDiscovery : No linked device found."); + res = OC_STACK_CONTINUE; + goto error; + } + + //2. Make a list of devices to send DELETE credential request + // by comparing owned devices from provisioning database with mutlicast discovery result. + size_t numOfLinkedDev = 0; + res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList, + &pLinkedDevList, &numOfLinkedDev); + if (OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : GetListofDevToReqDeleteCred() failed"); + goto error; + } + if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now. + { // So we don't have to send request message. + OIC_LOG(DEBUG, TAG, "SRPRemoveDeviceWithoutDiscovery : No alived & linked device found."); + res = OC_STACK_CONTINUE; + goto error; + } + + // 3. Prepare RemoveData Context data. + removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t)); + if (!removeData) + { + OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to memory allocation"); + res = OC_STACK_NO_MEMORY; + goto error; + } + + removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev); + if (!removeData->revokeTargetDev) + { + OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : PMCloneOCProvisionDev Failed"); + res = OC_STACK_NO_MEMORY; + goto error; + } + + removeData->removeRes = + (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t)); + if (!removeData->removeRes) + { + OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to memory allocation"); + res = OC_STACK_NO_MEMORY; + goto error; + } + + removeData->ctx = ctx; + removeData->linkedDevList = pLinkedDevList; + removeData->resultCallback = resultCallback; + removeData->numOfResults = 0; + removeData->sizeOfResArray = numOfLinkedDev; + removeData->hasError = false; + + // 5. Send DELETE credential request to linked devices. + OCProvisionDev_t *curDev = NULL, *tmpDev = NULL; + OCStackResult totalRes = OC_STACK_ERROR; /* variable for checking request is sent or not */ + LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev) + { + res = SendDeleteCredentialRequest((void*)removeData, &SRPRemoveDeviceCB, + removeData->revokeTargetDev, curDev); + if (OC_STACK_OK != res) + { + OIC_LOG_V(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Fail to send the DELETE credential request to\ + %s:%u", curDev->endpoint.addr, curDev->endpoint.port); + } + else + { + totalRes = OC_STACK_OK; // This means at least one request is successfully sent. + } + } + + PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention. + OIC_LOG(INFO, TAG, "OUT SRPRemoveDeviceWithoutDiscovery"); + + return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK. + +error: + PDMDestoryOicUuidLinkList(pLinkedUuidList); + PMDeleteDeviceList(pLinkedDevList); + if (removeData) + { + OICFree(removeData->revokeTargetDev); + OICFree(removeData->removeRes); + OICFree(removeData); + } + OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDeviceWithoutDiscovery"); + return res; +} + +/* + * Function to sync-up credential and ACL of the target device. + * This function will remove credential and ACL of target device from all devices in subnet. + * + * @param[in] ctx Application context would be returned in result callback + * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds) + * @param[in] pTargetDev Device information to be revoked. + * @param[in] resultCallback callback provided by API user, callback will be called when + * credential revocation is finished. + * when there is an error, this user callback is called immediately. + * @return OC_STACK_OK in case of success and other value otherwise. + * If OC_STACK_OK is returned, the caller of this API should wait for callback. + * OC_STACK_CONTINUE means operation is success but no request is need to be initiated. + */ +OCStackResult SRPSyncDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery, + const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback) +{ + OIC_LOG(INFO, TAG, "IN SRPSyncDevice"); + if (!pTargetDev || 0 == waitTimeForOwnedDeviceDiscovery) + { + OIC_LOG(INFO, TAG, "SRPSyncDevice : NULL parameters"); + return OC_STACK_INVALID_PARAM; + } + if (!resultCallback) + { + OIC_LOG(INFO, TAG, "SRPSyncDevice : NULL Callback"); + return OC_STACK_INVALID_CALLBACK; + } + + // Declare variables in here to handle error cases with goto statement. + OCProvisionDev_t* pOwnedDevList = NULL; + OCProvisionDev_t* pLinkedDevList = NULL; + RemoveData_t* removeData = NULL; + + //1. Find all devices that has a credential of the revoked device + OCUuidList_t* pLinkedUuidList = NULL; + size_t numOfDevices = 0; + OCStackResult res = OC_STACK_ERROR; + res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices); + if (OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to get linked devices information"); + return res; + } + // if there is no related device, we can skip further process. + if (0 == numOfDevices) + { + OIC_LOG(DEBUG, TAG, "SRPSyncDevice : No linked device found."); + res = OC_STACK_CONTINUE; + goto error; + } + + //2. Find owned device from the network + res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList); + if (OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to PMDeviceDiscovery"); + goto error; + } + + //3. Make a list of devices to send DELETE credential request + // by comparing owned devices from provisioning database with mutlicast discovery result. + size_t numOfLinkedDev = 0; + res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList, + &pLinkedDevList, &numOfLinkedDev); + if (OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "SRPSyncDevice : GetListofDevToReqDeleteCred() failed"); + goto error; + } + if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now. + { // So we don't have to send request message. + OIC_LOG(DEBUG, TAG, "SRPSyncDevice : No alived & linked device found."); + res = OC_STACK_CONTINUE; + goto error; + } + + // 4. Prepare RemoveData Context data. + removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t)); + if (!removeData) + { + OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to memory allocation"); + res = OC_STACK_NO_MEMORY; + goto error; + } + + removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev); + if (!removeData->revokeTargetDev) + { + OIC_LOG(ERROR, TAG, "SRPSyncDevice : PMCloneOCProvisionDev Failed"); + res = OC_STACK_NO_MEMORY; + goto error; + } + + removeData->removeRes = + (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t)); + if (!removeData->removeRes) + { + OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to allocate memory"); + res = OC_STACK_NO_MEMORY; + goto error; + } + + removeData->ctx = ctx; + removeData->linkedDevList = pLinkedDevList; + removeData->resultCallback = resultCallback; + removeData->numOfResults = 0; + removeData->sizeOfResArray = numOfLinkedDev; + removeData->hasError = false; + + // 5. Send DELETE credential request to linked devices. + OCProvisionDev_t *curDev = NULL, *tmpDev = NULL; + OCStackResult totalRes = OC_STACK_ERROR; /* variable for checking request is sent or not */ + LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev) + { + res = SendDeleteACLRequest((void*)removeData, &SRPSyncDeviceACLCB, + removeData->revokeTargetDev, curDev); + if (OC_STACK_OK != res) + { + OIC_LOG_V(ERROR, TAG, "SRPSyncDevice : Fail to send the DELETE ACL request to\ + %s:%u", curDev->endpoint.addr, curDev->endpoint.port); + goto error; + } + res = SendDeleteCredentialRequest((void*)removeData, &SRPSyncDeviceCredCB, + removeData->revokeTargetDev, curDev); + if (OC_STACK_OK != res) + { + OIC_LOG_V(ERROR, TAG, "SRPSyncDevice : Fail to send the DELETE credential request to\ + %s:%u", curDev->endpoint.addr, curDev->endpoint.port); + totalRes = OC_STACK_ERROR; + } + else + { + totalRes = OC_STACK_OK; // This means at least one request is successfully sent. + } + } + + PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention. + PMDeleteDeviceList(pOwnedDevList); + OIC_LOG(INFO, TAG, "OUT SRPSyncDevice"); + + return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK. + +error: + PDMDestoryOicUuidLinkList(pLinkedUuidList); + PMDeleteDeviceList(pOwnedDevList); + PMDeleteDeviceList(pLinkedDevList); + if (removeData) + { + OICFree(removeData->revokeTargetDev); + OICFree(removeData->removeRes); + OICFree(removeData); + } + OIC_LOG(INFO, TAG, "OUT ERROR case SRPSyncDevice"); + return res; +} + +/* + * Function for remote reset + * This function will send pstat PUT message to the target device to initiate remote reset. + * + * @param[in] pTargetDev Device information to be revoked. + * @param[in] resultCallback callback provided by API user, callback will be called when + * credential revocation is finished. + * when there is an error, this user callback is called immediately. + * @return OC_STACK_OK in case of success and other value otherwise. + * If OC_STACK_OK is returned, the caller of this API should wait for callback. + * OC_STACK_CONTINUE means operation is success but no request is need to be initiated. + */ +OCStackResult SRPResetDevice(const OCProvisionDev_t* pTargetDev, + OCProvisionResultCB resultCallback) +{ + OIC_LOG(INFO, TAG, "IN SRPResetDevice"); + if (!pTargetDev) + { + OIC_LOG(INFO, TAG, "SRPResetDevice : NULL parameters"); + return OC_STACK_INVALID_PARAM; + } + if (!resultCallback) + { + OIC_LOG(INFO, TAG, "SRPResetDevice : NULL Callback"); + return OC_STACK_INVALID_CALLBACK; + } + + OCStackResult res = OC_STACK_ERROR; + OicSecPstat_t * pstat = (OicSecPstat_t *) OICCalloc(1, sizeof(OicSecPstat_t)); + if (!pstat) + { + OIC_LOG(ERROR, TAG, "Failed to allocate memory"); + return OC_STACK_NO_MEMORY; + } + + pstat->cm = RESET; + pstat->isOp = false; + memcpy(pstat->deviceID.id, pTargetDev->doxm->deviceID.id, sizeof(OicUuid_t)); + pstat->tm = TAKE_OWNER; + pstat->om = (OicSecDpom_t)(SINGLE_SERVICE_SERVER_DRIVEN | MULTIPLE_SERVICE_CLIENT_DRIVEN); + pstat->smLen = 1; + pstat->sm = (OicSecDpom_t *) OICCalloc(pstat->smLen, sizeof(OicSecDpom_t)); + if (NULL == pstat->sm) + { + OIC_LOG(ERROR, TAG, "Failed to allocate memory"); + OICFree(pstat); + return OC_STACK_NO_MEMORY; + } + pstat->sm[0] = (OicSecDpom_t)(SINGLE_SERVICE_SERVER_DRIVEN | MULTIPLE_SERVICE_CLIENT_DRIVEN); + + OCSecurityPayload * secPayload = (OCSecurityPayload *) OICCalloc(1, sizeof(OCSecurityPayload)); + if (!secPayload) + { + OIC_LOG(ERROR, TAG, "Failed to allocate memory"); + res = OC_STACK_NO_MEMORY; + goto error; + } + secPayload->base.type = PAYLOAD_TYPE_SECURITY; + + if (OC_STACK_OK != PstatToCBORPayload(pstat, &(secPayload->securityData), + &(secPayload->payloadSize), true)) + { + OCPayloadDestroy((OCPayload *) secPayload); + OIC_LOG(ERROR, TAG, "Failed to PstatToCBORPayload"); + res = OC_STACK_NO_MEMORY; + goto error; + } + OIC_LOG(DEBUG, TAG, "Created payload for pstat set"); + OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize); + + char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0}; + if (!PMGenerateQuery(true, + pTargetDev->endpoint.addr, + pTargetDev->securePort, + pTargetDev->connType, + query, sizeof(query), OIC_RSRC_PSTAT_URI)) + { + OIC_LOG(ERROR, TAG, "SRPResetDevice : Failed to generate query"); + OCPayloadDestroy((OCPayload *) secPayload); + res = OC_STACK_ERROR; + goto error; + } + OIC_LOG_V(DEBUG, TAG, "Query=%s", query); + + OCProvisionDev_t * targetDev = PMCloneOCProvisionDev(pTargetDev); + OCCallbackData cbData = { .context = NULL, .cb = NULL, .cd = NULL }; + cbData.cb = &SRPResetDeviceCB; + cbData.context = (void *) targetDev; + cbData.cd = NULL; + OCMethod method = OC_REST_POST; + OCDoHandle handle = NULL; + OIC_LOG(DEBUG, TAG, "Sending PSTAT info to resource server"); + res = OCDoResource(&handle, method, query, + &targetDev->endpoint, (OCPayload *)secPayload, + targetDev->connType, OC_LOW_QOS, &cbData, NULL, 0);\ + if (OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "OCStack resource error"); + } + +error: + OICFree(pstat->sm); + OICFree(pstat); + OIC_LOG(INFO, TAG, "OUT SRPResetDevice"); + 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; +} diff --git a/resource/csdk/security/provisioning/unittest/SConscript b/resource/csdk/security/provisioning/unittest/SConscript index ee406d52f..120e6cc27 100644 --- a/resource/csdk/security/provisioning/unittest/SConscript +++ b/resource/csdk/security/provisioning/unittest/SConscript @@ -17,36 +17,42 @@ # // limitations under the License. # // # //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -# -Import('env') import os import os.path -sptest_env = env.Clone() +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +sptest_env = gtest_env.Clone() src_dir = sptest_env.get('SRC_DIR') +target_os = sptest_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' ]) -sptest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) -sptest_env.AppendUnique(LIBS = ['-lpthread','-ldl']) -sptest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) -sptest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs']) +sptest_env.AppendUnique(LIBPATH = [sptest_env.get('BUILD_DIR')]) sptest_env.PrependUnique(LIBS = [ 'ocpmapi', 'oc', 'ocsrm', @@ -57,36 +63,48 @@ sptest_env.PrependUnique(LIBS = [ 'ocpmapi', 'gtest', 'gtest_main']) -if env.get('SECURED') == '1': +if sptest_env.get('SECURED') == '1': sptest_env.AppendUnique(LIBS = ['tinydtls']) -if env.get('DTLS_WITH_X509') == '1': + +if sptest_env.get('DTLS_WITH_X509') == '1': sptest_env.AppendUnique(LIBS = ['CKManager']) sptest_env.AppendUnique(LIBS = ['asn1']) -if not env.get('RELEASE'): +if not sptest_env.get('RELEASE'): sptest_env.AppendUnique(CPPDEFINES = ['TB_LOG']) +if target_os not in ['msys_nt', 'windows']: + sptest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) + sptest_env.AppendUnique(LIBS = ['dl', 'pthread']) + ###################################################################### # Source files and Targets ###################################################################### -unittest = sptest_env.Program('unittest', ['pmutilitytest.cpp', 'otmunittest.cpp', +unittest = sptest_env.Program('unittest', ['pmutilitytest.cpp', 'secureresourceprovider.cpp', 'provisioningdatabasemanager.cpp', - 'ocprovisioningmanager.cpp' ]) + 'ocprovisioningmanager.cpp', 'otmunittest.cpp', + 'credentialgeneratortest.cpp' ]) + +sample_server1 = sptest_env.Program('sample_server1', ['sampleserver1.cpp']) +sample_server2 = sptest_env.Program('sample_server2', ['sampleserver2.cpp']) + +provisioning_unittest_src_dir = src_dir + '/resource/csdk/security/provisioning/unittest/' +provisioning_unittest_build_dir = sptest_env.get('BUILD_DIR') +'/resource/csdk/security/provisioning/unittest/' + +Alias("test", [unittest, 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': - out_dir = env.get('BUILD_DIR') - result_dir = env.get('BUILD_DIR') + '/test_out/' +sptest_env.AppendTarget('test') +if sptest_env.get('TEST') == '1': + if target_os in ['linux']: + out_dir = sptest_env.get('BUILD_DIR') + result_dir = os.path.join(sptest_env.get('BUILD_DIR'), 'test_out') + os.sep 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('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs']) + sptest_env.AppendENVPath('PATH', sptest_env.get('BUILD_DIR')) 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 index 000000000..52a034b28 --- /dev/null +++ b/resource/csdk/security/provisioning/unittest/credentialgeneratortest.cpp @@ -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__ + diff --git a/resource/csdk/security/provisioning/unittest/ocprovisioningmanager.cpp b/resource/csdk/security/provisioning/unittest/ocprovisioningmanager.cpp index b10129aad..ac738cf14 100644 --- a/resource/csdk/security/provisioning/unittest/ocprovisioningmanager.cpp +++ b/resource/csdk/security/provisioning/unittest/ocprovisioningmanager.cpp @@ -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; @@ -134,6 +146,16 @@ TEST(OCRemoveDeviceTest, NullTargetDevice) EXPECT_EQ(OC_STACK_INVALID_PARAM, OCRemoveDevice(NULL, waitTime, NULL, provisioningCB)); } +TEST(OCRemoveDeviceWithUuidTest, NullTargetDevice) +{ + unsigned short waitTime = 10 ; + OicUuid_t uuid; + EXPECT_EQ(OC_STACK_INVALID_PARAM, OCRemoveDeviceWithUuid(NULL, waitTime, NULL, provisioningCB)); + + EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCRemoveDeviceWithUuid(NULL, waitTime, &uuid, NULL)); +} + + TEST(OCRemoveDeviceTest, NullResultCallback) { unsigned short waitTime = 10; @@ -174,3 +196,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)); +} diff --git a/resource/csdk/security/provisioning/unittest/otmunittest.cpp b/resource/csdk/security/provisioning/unittest/otmunittest.cpp index f0a0eabfa..00aa699e7 100644 --- a/resource/csdk/security/provisioning/unittest/otmunittest.cpp +++ b/resource/csdk/security/provisioning/unittest/otmunittest.cpp @@ -17,12 +17,24 @@ * 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 index 000000000..056e8c113 --- /dev/null +++ b/resource/csdk/security/provisioning/unittest/sampleserver1.cpp @@ -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 index 000000000..c500ec7db --- /dev/null +++ b/resource/csdk/security/provisioning/unittest/sampleserver2.cpp @@ -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; +} diff --git a/resource/csdk/security/src/aclresource.c b/resource/csdk/security/src/aclresource.c index d2b9f4b1d..2c50fec0b 100644 --- a/resource/csdk/security/src/aclresource.c +++ b/resource/csdk/security/src/aclresource.c @@ -25,7 +25,9 @@ #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,11 +47,12 @@ #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_MAP_SIZE = 4; static const uint8_t ACL_ACLIST_MAP_SIZE = 1; static const uint8_t ACL_ACES_MAP_SIZE = 3; -static const uint8_t ACL_RESOURCE_MAP_SIZE = 4; +static const uint8_t ACL_RESOURCE_MAP_SIZE = 3; // CborSize is the default cbor payload size being used. @@ -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->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) { - LL_DELETE(acl, aclTmp1); - FreeACE(aclTmp1); + 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,166 @@ 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); + size_t rsrcMapSize = ACL_RESOURCE_MAP_SIZE; + if(rsrc->rel) + { + rsrcMapSize++; + } + + cborEncoderResult = cbor_encoder_create_map(&resources, &rMap, rsrcMapSize); 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."); + } 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 @@ -357,6 +564,38 @@ OCStackResult AclToCBORPayload(const OicSecAcl_t *secAcl, uint8_t **payload, siz OICFree(rowner); } + //RT -- Mandatory + CborEncoder rtArray; + cborEncoderResult = cbor_encode_text_string(&aclMap, OIC_JSON_RT_NAME, + strlen(OIC_JSON_RT_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag."); + cborEncoderResult = cbor_encoder_create_array(&aclMap, &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_ACL, + strlen(OIC_RSRC_TYPE_SEC_ACL)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value."); + } + cborEncoderResult = cbor_encoder_close_container(&aclMap, &rtArray); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT."); + + //IF-- Mandatory + CborEncoder ifArray; + cborEncoderResult = cbor_encode_text_string(&aclMap, OIC_JSON_IF_NAME, + strlen(OIC_JSON_IF_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag."); + cborEncoderResult = cbor_encoder_create_array(&aclMap, &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(&aclMap, &ifArray); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF."); + // Close ACL Map cborEncoderResult = cbor_encoder_close_container(&encoder, &aclMap); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACL Map."); @@ -409,7 +648,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 +680,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 +732,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 +750,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 +760,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 +776,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 +852,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 +938,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 +961,11 @@ exit: if (cborFindResult != CborNoError) { OIC_LOG(ERROR, TAG, "Failed to CBORPayloadToAcl"); - DeleteACLList(headAcl); - headAcl = NULL; + DeleteACLList(acl); + acl = NULL; } - return headAcl; + + return acl; } /** @@ -716,12 +979,12 @@ exit: * ::OC_STACK_NO_RESOURCE on failure to find the appropriate ACE * ::OC_STACK_INVALID_PARAM on invalid parameter */ -static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource) +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 +997,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 +1013,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(acl->resources[i], resource) == 0) - { - resPos = i; - break; - } - } - if (0 <= (int) resPos) + if(strcmp(rsrc->href, resource) == 0) { - 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 +1083,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; } } @@ -875,6 +1128,203 @@ exit: return false; } +static size_t GetNumberOfResource(OicSecRsrc_t* resources) +{ + size_t ret = 0; + if(resources) + { + OicSecRsrc_t* rsrc = NULL; + LL_FOREACH(resources, rsrc) + { + ret++; + } + } + return ret; +} + +static size_t GetNumberOfValidity(OicSecValidity_t* val) +{ + size_t ret = 0; + + if(val) + { + OicSecValidity_t* temp = NULL; + LL_FOREACH(val, temp) + { + ret++; + } + } + return ret; +} + + +static bool IsSameStringArray(char** strArr1, size_t strArr1Len, + char** strArr2, size_t strArr2Len) +{ + + if(NULL == strArr1 && NULL == strArr2) + { + return true; + } + + if(strArr1 && strArr2 && NULL == *strArr1 && NULL == *strArr2) + { + return true; + } + + if(strArr1 && strArr2) + { + if(*strArr1 && *strArr2 && strArr1Len == strArr2Len) + { + size_t matchedStr = 0; + for(size_t i = 0; i < strArr1Len; i++) + { + for(size_t j = 0; j < strArr2Len; j++) + { + if(strcmp(strArr1[i], strArr2[j]) == 0) + { + matchedStr++; + } + } + } + if(matchedStr == strArr1Len) + { + return true; + } + } + } + + return false; +} + +static bool IsSameResources(OicSecRsrc_t* resources1, OicSecRsrc_t* resources2) +{ + size_t numOfRsrc1 = 0; + size_t numOfRsrc2 = 0; + size_t numOfMatchedRsrc = 0; + OicSecRsrc_t* rsrc1 = NULL; + OicSecRsrc_t* rsrc2 = NULL; + + if(NULL == resources1 && NULL == resources2) + { + return true; + } + + if(resources1 && resources2) + { + numOfRsrc1 = GetNumberOfResource(resources1); + numOfRsrc2 = GetNumberOfResource(resources2); + + if(0 == numOfRsrc1 && 0 == numOfRsrc2) + { + return true; + } + + LL_FOREACH(resources1, rsrc1) + { + rsrc2 = NULL; + LL_FOREACH(resources2, rsrc2) + { + if(rsrc1 && rsrc2) + { + if(strcmp(rsrc1->href, rsrc2->href) == 0 && + IsSameStringArray(rsrc1->interfaces, rsrc1->interfaceLen, + rsrc2->interfaces, rsrc2->interfaceLen) && + IsSameStringArray(rsrc1->types, rsrc1->typeLen, + rsrc2->types, rsrc2->typeLen)) + { + // TODO: Update codes to compare 'rel' property + numOfMatchedRsrc++; + } + } + } + } + + if(numOfMatchedRsrc == numOfRsrc1) + { + return true; + } + } + + return false; +} + +static bool IsSameValidities(OicSecValidity_t* validities1, OicSecValidity_t* validities2) +{ + size_t numOfVal1 = 0; + size_t numOfVal2 = 0; + size_t numOfMatchedVal = 0; + OicSecValidity_t* val1 = NULL; + OicSecValidity_t* val2 = NULL; + + if(NULL == validities1 && NULL == validities2) + { + return true; + } + + if(validities1 && validities2) + { + numOfVal1 = GetNumberOfValidity(validities1); + numOfVal2 = GetNumberOfValidity(validities2); + if(0 == numOfVal1 && 0 == numOfVal2) + { + return true; + } + + if(numOfVal1 == numOfVal2) + { + LL_FOREACH(validities1, val1) + { + LL_FOREACH(validities2, val2) + { + if(strcmp(val1->period, val2->period) == 0 && + IsSameStringArray(val1->recurrences, val1->recurrenceLen, + val2->recurrences, val2->recurrenceLen)) + { + numOfMatchedVal++; + } + } + } + if(numOfVal1 == numOfMatchedVal) + { + return true; + } + } + } + + return false; +} + +static bool IsSameACE(OicSecAce_t* ace1, OicSecAce_t* ace2) +{ + if(ace1 && ace2) + { + if(memcmp(ace1->subjectuuid.id, ace2->subjectuuid.id, sizeof(ace1->subjectuuid.id)) != 0) + { + return false; + } + + if(false == IsSameResources(ace1->resources, ace2->resources)) + { + return false; + } + + if(ace1->permission != ace2->permission) + { + return false; + } + + if(false == IsSameValidities(ace1->validities, ace2->validities)) + { + return false; + } + + return true; + } + + return false; +} + static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *ehRequest) { OIC_LOG(INFO, TAG, "HandleACLGetRequest processing the request"); @@ -882,20 +1332,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 +1359,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 +1385,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 +1393,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)) { @@ -948,13 +1406,13 @@ static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *e exit: // A device should always have a default acl. Therefore, payload should never be NULL. ehRet = (payload ? OC_EH_OK : OC_EH_ERROR); + OIC_LOG(DEBUG, TAG, "ACL payload with GET response"); + OIC_LOG_BUFFER(DEBUG, TAG, payload, size); + + //Send payload to request originator + ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ? + OC_EH_OK : OC_EH_ERROR; - // Send response payload to request originator - if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, payload, size)) - { - ehRet = OC_EH_ERROR; - OIC_LOG(ERROR, TAG, "SendSRMResponse failed for HandleACLGetRequest"); - } OICFree(payload); OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__, ehRet); @@ -964,46 +1422,82 @@ exit: static OCEntityHandlerResult HandleACLPostRequest(const OCEntityHandlerRequest *ehRequest) { OIC_LOG(INFO, TAG, "HandleACLPostRequest processing the request"); - OCEntityHandlerResult ehRet = OC_EH_ERROR; + OCEntityHandlerResult ehRet = OC_EH_OK; // Convert CBOR into ACL data and update to SVR buffers. This will also validate the ACL data received. uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData; size_t size = ((OCSecurityPayload *) ehRequest->payload)->payloadSize; if (payload) { - OicSecAcl_t *newAcl = CBORPayloadToAcl(payload, size); + OicSecAcl_t *newAcl = NULL; + OicSecAcl_t newAceList; + OIC_LOG(DEBUG, TAG, "ACL payload from POST request << "); + OIC_LOG_BUFFER(DEBUG, TAG, payload, size); + + newAcl = CBORPayloadToAcl(payload, size); 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) + bool isNewAce = true; + OicSecAce_t* existAce = NULL; + OicSecAce_t* newAce = NULL; + OicSecAce_t* tempAce1 = NULL; + OicSecAce_t* tempAce2 = NULL; + newAceList.aces = NULL; + + LL_FOREACH_SAFE(newAcl->aces, newAce, tempAce1) { - ehRet = OC_EH_RESOURCE_CREATED; + isNewAce = true; + LL_FOREACH_SAFE(gAcl->aces, existAce, tempAce2) + { + if(IsSameACE(newAce, existAce)) + { + isNewAce = false; + } + } + if(isNewAce) + { + OIC_LOG(DEBUG, TAG, "NEW ACE dectected."); + + OicSecAce_t* insertAce = DuplicateACE(newAce); + if(insertAce) + { + OIC_LOG(DEBUG, TAG, "Appending new ACE.."); + LL_PREPEND(gAcl->aces, insertAce); + } + else + { + OIC_LOG(ERROR, TAG, "Failed to duplicate ACE."); + ehRet = OC_EH_ERROR; + } + } } - else + + DeleteACLList(newAcl); + + if(OC_EH_OK == ehRet) { + size_t size = 0; uint8_t *cborPayload = NULL; if (OC_STACK_OK == AclToCBORPayload(gAcl, &cborPayload, &size)) { if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, cborPayload, size) == OC_STACK_OK) { - ehRet = OC_EH_RESOURCE_CREATED; + ehRet = OC_EH_CHANGED; } OICFree(cborPayload); } + + if(OC_EH_CHANGED != ehRet) + { + ehRet = OC_EH_ERROR; + } } } } - // Send payload to request originator - if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0)) - { - ehRet = OC_EH_ERROR; - OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleACLPostRequest"); - } + //Send response to request originator + ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ? + OC_EH_OK : OC_EH_ERROR; OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__, ehRet); return ehRet; @@ -1029,12 +1523,9 @@ static OCEntityHandlerResult HandleACLDeleteRequest(const OCEntityHandlerRequest } exit: - // Send payload to request originator - if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0)) - { - ehRet = OC_EH_ERROR; - OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleACLDeleteRequest"); - } + //Send response to request originator + ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ? + OC_EH_OK : OC_EH_ERROR; return ehRet; } @@ -1070,8 +1561,8 @@ OCEntityHandlerResult ACLEntityHandler(OCEntityHandlerFlag flag, OCEntityHandler break; default: - ehRet = OC_EH_ERROR; - SendSRMResponse(ehRequest, ehRet, NULL, 0); + ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ? + OC_EH_OK : OC_EH_ERROR; } } @@ -1087,7 +1578,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 +1602,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 +1619,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 +1761,6 @@ OCStackResult GetDefaultACL(OicSecAcl_t** defaultAcl) memcpy(&acl->rownerID, &ownerId, sizeof(OicUuid_t)); - acl->next = NULL; - *defaultAcl = acl; ret = OC_STACK_OK; @@ -1202,7 +1783,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 +1799,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 +1832,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 +1848,7 @@ const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t ** */ if (NULL == *savePtr) { - begin = gAcl; + begin = gAcl->aces; } else { @@ -1272,22 +1857,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 +1891,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 +1913,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++) + { + 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++) { - 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->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; + newAce->validities = 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)); - - 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 +2041,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 +2051,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; diff --git a/resource/csdk/security/src/amaclresource.c b/resource/csdk/security/src/amaclresource.c index be21257fa..6dd9c1415 100644 --- a/resource/csdk/security/src/amaclresource.c +++ b/resource/csdk/security/src/amaclresource.c @@ -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); @@ -488,7 +478,7 @@ static OCEntityHandlerResult HandleAmaclPostRequest (const OCEntityHandlerReques if (cborPayload && (OC_STACK_OK == res) && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_AMACL_NAME, cborPayload, size))) { - ehRet = OC_EH_RESOURCE_CREATED; + ehRet = OC_EH_CHANGED; } OICFree(cborPayload); } @@ -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, diff --git a/resource/csdk/security/src/amsmgr.c b/resource/csdk/security/src/amsmgr.c index 9486f9025..0ce3e7677 100644 --- a/resource/csdk/security/src/amsmgr.c +++ b/resource/csdk/security/src/amsmgr.c @@ -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] = {}; OCCallbackData cbData = {.context=NULL}; OCDevAddr destAddr = {.adapter = OC_ADAPTER_IP}; - B64Result b64Ret; char *subID = NULL; VERIFY_NON_NULL(TAG, context, ERROR); @@ -327,6 +324,11 @@ OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endp { OCStackResult ret = OC_STACK_ERROR; + if (!context->amsMgrContext) + { + goto exit; + } + //The AmsMgr context endpoint and requestInfo will be free from , //AmsMgrAclReqCallback function if (context->amsMgrContext->endpoint) @@ -354,7 +356,7 @@ void FreeCARequestInfo(CARequestInfo_t *requestInfo) { if (NULL == requestInfo) { - OIC_LOG_V(ERROR, TAG, "%s: Can't free memory. Received NULL requestInfo", __func__); + OIC_LOG_V(DEBUG, TAG, "%s: Can't free memory. Received NULL requestInfo", __func__); return; } OICFree(requestInfo->info.token); diff --git a/resource/csdk/security/src/credresource.c b/resource/csdk/security/src/credresource.c index 07bc8ea16..d22c9837d 100644 --- a/resource/csdk/security/src/credresource.c +++ b/resource/csdk/security/src/credresource.c @@ -62,10 +62,9 @@ static const uint16_t CBOR_SIZE = 2048; static const uint16_t CBOR_MAX_SIZE = 4400; /** CRED size - Number of mandatory items. */ -static const uint8_t CRED_ROOT_MAP_SIZE = 2; +static const uint8_t CRED_ROOT_MAP_SIZE = 4; static const uint8_t CRED_MAP_SIZE = 3; - static OicSecCred_t *gCred = NULL; static OCResourceHandle gCredHandle = NULL; @@ -124,7 +123,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 +179,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 +244,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 +256,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."); @@ -311,6 +335,39 @@ OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload OICFree(rowner); } + //RT -- Mandatory + CborEncoder rtArray; + cborEncoderResult = cbor_encode_text_string(&credRootMap, OIC_JSON_RT_NAME, + strlen(OIC_JSON_RT_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag."); + cborEncoderResult = cbor_encoder_create_array(&credRootMap, &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_CRED, + strlen(OIC_RSRC_TYPE_SEC_CRED)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value."); + } + cborEncoderResult = cbor_encoder_close_container(&credRootMap, &rtArray); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT."); + + //IF-- Mandatory + CborEncoder ifArray; + cborEncoderResult = cbor_encode_text_string(&credRootMap, OIC_JSON_IF_NAME, + strlen(OIC_JSON_IF_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag."); + cborEncoderResult = cbor_encoder_create_array(&credRootMap, &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(&credRootMap, &ifArray); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF."); + + // Close CRED Root Map cborEncoderResult = cbor_encoder_close_container(&encoder, &credRootMap); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing CRED Root Map."); @@ -332,7 +389,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 +432,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 +476,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 +492,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 +510,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 +525,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 +538,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 +601,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 +612,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 +658,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 +729,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 +775,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 +965,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 +1007,24 @@ 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"); + static uint16_t previousMsgId = 0; //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) @@ -897,7 +1042,7 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR OIC_LOG(ERROR, TAG, "OwnerPSK was generated successfully."); if(OC_STACK_OK == AddCredential(cred)) { - ret = OC_EH_RESOURCE_CREATED; + ret = OC_EH_CHANGED; } else { @@ -911,7 +1056,7 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR ret = OC_EH_ERROR; } - if(OC_EH_RESOURCE_CREATED == ret) + if(OC_EH_CHANGED == ret) { /** * in case of random PIN based OxM, @@ -969,14 +1114,27 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR } } - if(OC_EH_RESOURCE_CREATED != ret) + if(OC_EH_CHANGED != ret) { /* * If some error is occured while ownership transfer, * ownership transfer related resource should be revert back to initial status. */ - RestoreDoxmToInitState(); - RestorePstatToInitState(); + const OicSecDoxm_t* doxm = GetDoxmResourceData(); + if(doxm) + { + if(!doxm->owned && previousMsgId != ehRequest->messageID) + { + OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\ + "DOXM will be reverted."); + RestoreDoxmToInitState(); + RestorePstatToInitState(); + } + } + else + { + OIC_LOG(ERROR, TAG, "Invalid DOXM resource"); + } } } else @@ -987,7 +1145,7 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR * 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; + ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_CHANGED : OC_EH_ERROR; } #else //not __WITH_DTLS__ /* @@ -996,11 +1154,11 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR * 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; + ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_CHANGED : OC_EH_ERROR; #endif//__WITH_DTLS__ } - if (OC_EH_RESOURCE_CREATED != ret) + if (OC_EH_CHANGED != ret) { if(OC_STACK_OK != RemoveCredential(&cred->subject)) { @@ -1008,29 +1166,42 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR } FreeCred(cred); } - OIC_LOG(DEBUG, TAG, "HandleCREDPutRequest OUT"); + else + { + previousMsgId = ehRequest->messageID; + } + //Send response to request originator + ret = ((SendSRMResponse(ehRequest, ret, NULL, 0)) == OC_STACK_OK) ? + OC_EH_OK : OC_EH_ERROR; + + 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) - { - //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; - } + // Convert Cred data into CBOR for transmission + size_t size = 0; + uint8_t *payload = NULL; + int secureFlag = 1; - return ret; + 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 payload to request originator + ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ? + OC_EH_OK : OC_EH_ERROR; + OICFree(payload); + return ehRet; } static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *ehRequest) @@ -1063,7 +1234,9 @@ static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *e { ehRet = OC_EH_RESOURCE_DELETED; } - + //Send response to request originator + ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ? + OC_EH_OK : OC_EH_ERROR; exit: return ehRet; } @@ -1082,15 +1255,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; @@ -1098,15 +1269,11 @@ OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag, ret = HandleDeleteRequest(ehRequest); break; default: - ret = OC_EH_ERROR; + ret = ((SendSRMResponse(ehRequest, ret, NULL, 0)) == OC_STACK_OK) ? + OC_EH_OK : OC_EH_ERROR; break; } } - - //Send payload to request originator - ret = (SendSRMResponse(ehRequest, ret, NULL, 0) == OC_STACK_OK) ? - ret : OC_EH_ERROR; - return ret; } @@ -1114,11 +1281,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) { @@ -1247,15 +1414,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 +1458,6 @@ int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type, default: { OIC_LOG (ERROR, TAG, "Wrong value passed for CADtlsPskCredType_t."); - ret = -1; } break; } @@ -1297,7 +1490,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 +1601,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 +1618,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); diff --git a/resource/csdk/security/src/crlresource.c b/resource/csdk/security/src/crlresource.c index 53f2ca2df..99159dee2 100644 --- a/resource/csdk/security/src/crlresource.c +++ b/resource/csdk/security/src/crlresource.c @@ -305,7 +305,7 @@ static OCEntityHandlerResult HandleCRLPostRequest(const OCEntityHandlerRequest * if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_CBOR_CRL_NAME, payload, size)) { - ehRet = OC_EH_RESOURCE_CREATED; + ehRet = OC_EH_CHANGED; } DeleteCrlBinData(crl); @@ -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); } diff --git a/resource/csdk/security/src/directpairing.c b/resource/csdk/security/src/directpairing.c index 560659862..8e8712bc6 100644 --- a/resource/csdk/security/src/directpairing.c +++ b/resource/csdk/security/src/directpairing.c @@ -65,6 +65,7 @@ typedef struct DPairData OCDirectPairingDev_t *peer; /**< Pointer to pairing target info.**/
char pin[DP_PIN_LENGTH]; /**< PIN **/
OCDirectPairingResultCB resultCallback; /**< Pointer to result callback.**/
+ void *userCtx; /** < user context to pass in callback **/
} DPairData_t;
static OCDirectPairingDev_t *g_dp_paired = NULL;
@@ -331,7 +332,7 @@ static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHand if (clientResponse)
{
- if(OC_STACK_OK == clientResponse->result)
+ if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
{
// result
OIC_LOG(INFO, TAG, "DirectPairingFinalizeHandler : success PUT"
@@ -347,7 +348,7 @@ static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHand if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))
{
OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
- resultCallback(peer, OC_STACK_ERROR);
+ resultCallback(dpairData->userCtx, peer, OC_STACK_ERROR);
return OC_STACK_DELETE_TRANSACTION;
}
@@ -356,7 +357,7 @@ static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHand if(OC_STACK_OK != res)
{
OIC_LOG(ERROR, TAG, "Failed to PairingPSK generation");
- resultCallback(peer, res);
+ resultCallback(dpairData->userCtx, peer, res);
return OC_STACK_DELETE_TRANSACTION;
}
@@ -385,7 +386,7 @@ static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHand OIC_LOG(ERROR, TAG, "Error while adding a device to paired list.");
}
- resultCallback(peer, OC_STACK_OK);
+ resultCallback(dpairData->userCtx, peer, OC_STACK_OK);
return OC_STACK_DELETE_TRANSACTION;
}
@@ -399,7 +400,7 @@ static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHand OIC_LOG(ERROR, TAG, "DirectPairingFinalizeHandler received Null clientResponse");
}
- resultCallback(peer, OC_STACK_ERROR);
+ resultCallback(dpairData->userCtx, peer, OC_STACK_ERROR);
OICFree(dpairData);
return OC_STACK_DELETE_TRANSACTION;
}
@@ -412,7 +413,7 @@ static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHand *
* @return OC_STACK_OK on success otherwise error.
*/
-OCStackResult FinalizeDirectPairing(OCDirectPairingDev_t* peer,
+OCStackResult FinalizeDirectPairing(void *ctx, OCDirectPairingDev_t* peer,
OCDirectPairingResultCB resultCallback)
{
if(NULL == peer)
@@ -474,6 +475,7 @@ OCStackResult FinalizeDirectPairing(OCDirectPairingDev_t* peer, }
dpairData->peer = peer;
dpairData->resultCallback = resultCallback;
+ dpairData->userCtx = ctx;
OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
cbData.cb = DirectPairingFinalizeHandler;
@@ -525,17 +527,17 @@ void DirectPairingDTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInf {
OIC_LOG(INFO, TAG, "Now, finalize Direct-Pairing procedure.");
- res = FinalizeDirectPairing(peer, resultCallback);
+ res = FinalizeDirectPairing(g_dp_proceed_ctx->userCtx, peer, resultCallback);
if(OC_STACK_OK != res)
{
OIC_LOG(ERROR, TAG, "Failed to finalize direct-pairing");
- resultCallback(peer, res);
+ resultCallback(g_dp_proceed_ctx->userCtx, peer, res);
}
}
else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
{
OIC_LOG(INFO, TAG, "DirectPairingDTLSHandshakeCB - Authentication failed");
- resultCallback(peer, OC_STACK_AUTHENTICATION_FAILURE);
+ resultCallback(g_dp_proceed_ctx->userCtx, peer, OC_STACK_AUTHENTICATION_FAILURE);
}
#ifdef __WITH_DTLS__
@@ -586,7 +588,7 @@ static OCStackApplicationResult DirectPairingHandler(void *ctx, OCDoHandle UNUSE if (clientResponse)
{
- if(OC_STACK_RESOURCE_CREATED == clientResponse->result)
+ if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
{
// result
OIC_LOG(INFO, TAG, "DirectPairingHandler : success POST request to /oic/sec/dpairing");
@@ -653,7 +655,7 @@ exit: g_dp_proceed_ctx = NULL;
}
- resultCallback(dpairData->peer, res);
+ resultCallback(dpairData->userCtx, dpairData->peer, res);
}
OIC_LOG_V(INFO, TAG, "OUT DirectPairingHandler.");
return OC_STACK_DELETE_TRANSACTION;
@@ -668,8 +670,8 @@ exit: *
* @return OC_STACK_OK on success otherwise error.
*/
-OCStackResult DPDirectPairing(OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, char *pinNumber,
- OCDirectPairingResultCB resultCallback)
+OCStackResult DPDirectPairing(void *ctx, OCDirectPairingDev_t* peer, OicSecPrm_t pmSel,
+ char *pinNumber, OCDirectPairingResultCB resultCallback)
{
if(NULL == peer || NULL == pinNumber)
{
@@ -732,6 +734,7 @@ OCStackResult DPDirectPairing(OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, cha dpairData->peer = peer;
memcpy(dpairData->pin, pinNumber, DP_PIN_LENGTH);
dpairData->resultCallback = resultCallback;
+ dpairData->userCtx = ctx;
OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
cbData.cb = DirectPairingHandler;
@@ -1008,6 +1011,7 @@ OCStackResult DPDeviceDiscovery(unsigned short waittime) }
else
{
+ OCProcess();
nanosleep(&timeout, NULL);
}
}
diff --git a/resource/csdk/security/src/doxmresource.c b/resource/csdk/security/src/doxmresource.c index d48c8efeb..530e9b652 100644 --- a/resource/csdk/security/src/doxmresource.c +++ b/resource/csdk/security/src/doxmresource.c @@ -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; @@ -81,6 +81,14 @@ static OicSecDoxm_t gDefaultDoxm = {.id = {0}}, /* OicUuid_t rownerID */ }; +/** + * This method is internal method. + * the param roParsed is optionally used to know whether cborPayload has + * at least read only property value or not. + */ +static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size, + OicSecDoxm_t **doxm, bool *roParsed); + void DeleteDoxmBinData(OicSecDoxm_t* doxm) { if (doxm) @@ -100,7 +108,8 @@ void DeleteDoxmBinData(OicSecDoxm_t* doxm) } } -OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size) +OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size, + bool rwOnly) { if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size) { @@ -159,7 +168,7 @@ OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, siz } //Oxm -- Not Mandatory - if (doxm->oxmLen > 0) + if (doxm->oxmLen > 0 && false == rwOnly) { CborEncoder oxm; cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME, @@ -185,11 +194,14 @@ OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, siz VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value."); //sct -- Mandatory - cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, - strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME)); - VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag"); - cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct); - VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value."); + if (false == rwOnly) + { + cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, + strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag"); + cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value."); + } //Owned -- Mandatory cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME, @@ -198,16 +210,19 @@ OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, siz cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value."); - //DeviceId -- Mandatory - cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME, - strlen(OIC_JSON_DEVICE_ID_NAME)); - VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag."); - ret = ConvertUuidToStr(&doxm->deviceID, &strUuid); - VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR); - cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid)); - VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value."); - OICFree(strUuid); - strUuid = NULL; + if (false == rwOnly) + { + //DeviceId -- Mandatory + cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME, + strlen(OIC_JSON_DEVICE_ID_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag."); + ret = ConvertUuidToStr(&doxm->deviceID, &strUuid); + VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR); + cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value."); + OICFree(strUuid); + strUuid = NULL; + } //devownerid -- Mandatory cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME, @@ -231,13 +246,45 @@ OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, siz OICFree(strUuid); strUuid = NULL; - //DPC -- Mandatory + //x.org.iotivity.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."); @@ -257,7 +304,7 @@ exit: cborLen += encoder.ptr - encoder.end; OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen); cborEncoderResult = CborNoError; - ret = DoxmToCBORPayload(doxm, payload, &cborLen); + ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly); *size = cborLen; } @@ -276,6 +323,12 @@ exit: OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size, OicSecDoxm_t **secDoxm) { + return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL); +} + +static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size, + OicSecDoxm_t **secDoxm, bool *roParsed) +{ if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size) { return OC_STACK_INVALID_PARAM; @@ -313,7 +366,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,13 +392,30 @@ 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") cborFindResult = cbor_value_advance(&oxm); VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.") } + + if (roParsed) + { + *roParsed = true; + } + } + else + { + VERIFY_NON_NULL(TAG, gDoxm, ERROR); + doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm)); + VERIFY_NON_NULL(TAG, doxm->oxm, ERROR); + doxm->oxmLen = gDoxm->oxmLen; + int i; + for (i = 0; i < gDoxm->oxmLen; i++) + { + doxm->oxm[i] = gDoxm->oxm[i]; + } } cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap); @@ -365,6 +435,11 @@ OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size, { cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->sct); VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.") + + if (roParsed) + { + *roParsed = true; + } } else // PUT/POST JSON may not have sct so set it to the gDoxm->sct { @@ -390,10 +465,10 @@ OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size, cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->dpc); VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DPC Value.") } - else // PUT/POST JSON may not have owned so set it to the gDomx->owned + else // PUT/POST JSON may not have dpc so set it to the gDomx->dpc { VERIFY_NON_NULL(TAG, gDoxm, ERROR); - doxm->owned = false; + doxm->dpc = gDoxm->dpc; } cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap); @@ -405,6 +480,16 @@ OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size, VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR); OICFree(strUuid); strUuid = NULL; + + if (roParsed) + { + *roParsed = true; + } + } + else + { + VERIFY_NON_NULL(TAG, gDoxm, ERROR); + memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id)); } cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap); @@ -417,6 +502,11 @@ OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size, OICFree(strUuid); strUuid = NULL; } + else + { + VERIFY_NON_NULL(TAG, gDoxm, ERROR); + memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id)); + } cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap); if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap)) @@ -428,6 +518,11 @@ OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size, OICFree(strUuid); strUuid = NULL; } + else + { + VERIFY_NON_NULL(TAG, gDoxm, ERROR); + memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id)); + } *secDoxm = doxm; ret = OC_STACK_OK; @@ -457,7 +552,7 @@ static bool UpdatePersistentStorage(OicSecDoxm_t * doxm) // Convert Doxm data into CBOR for update to persistent storage uint8_t *payload = NULL; size_t size = 0; - OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size); + OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false); if (payload && (OC_STACK_OK == res) && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size))) { @@ -496,6 +591,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 +626,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 +650,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)) { @@ -561,29 +669,27 @@ static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest if (ehRet == OC_EH_OK) { - if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size)) + if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false)) { - payload = NULL; + OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest"); } } // Send response payload to request originator - if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, payload, size)) - { - ehRet = OC_EH_ERROR; - OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleDoxmGetRequest"); - } + ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ? + OC_EH_OK : OC_EH_ERROR; OICFree(payload); 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 @@ -595,13 +701,48 @@ static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest * { uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData; size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize; - OCStackResult res = CBORPayloadToDoxm(payload, size, &newDoxm); - + bool roParsed = false; + OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed); if (newDoxm && OC_STACK_OK == res) { - if (OIC_JUST_WORKS == newDoxm->oxmSel) + // Check request on RO property + if (true == roParsed) + { + OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys"); + ehRet = OC_EH_NOT_ACCEPTABLE; + goto exit; + } + + // in owned state + if (true == gDoxm->owned) { - if ((false == gDoxm->owned) && (false == newDoxm->owned)) + // update writable properties + gDoxm->oxmSel = newDoxm->oxmSel; + memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)); + memcpy(&(gDoxm->rownerID), &(newDoxm->rownerID), sizeof(OicUuid_t)); + + if(gDoxm->owned != newDoxm->owned) + { + gDoxm->owned = newDoxm->owned; + } + + //Update new state in persistent storage + if (UpdatePersistentStorage(gDoxm) == true) + { + ehRet = OC_EH_OK; + } + else + { + OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage"); + ehRet = OC_EH_ERROR; + } + goto exit; + } + + // in unowned state + if ((false == gDoxm->owned) && (false == newDoxm->owned)) + { + if (OIC_JUST_WORKS == newDoxm->oxmSel) { /* * If current state of the device is un-owned, enable @@ -649,10 +790,7 @@ static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest * #endif //__WITH_DTLS__ } } - } - else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel) - { - if ((false == gDoxm->owned) && (false == newDoxm->owned)) + else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel) { /* * If current state of the device is un-owned, enable @@ -683,25 +821,28 @@ 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; + } } #endif //__WITH_DTLS__ } @@ -778,8 +919,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; } @@ -801,23 +942,35 @@ static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest * exit: if(OC_EH_OK != ehRet) { - OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\ - "DOXM will be reverted."); /* * If some error is occured while ownership transfer, * ownership transfer related resource should be revert back to initial status. - */ - RestoreDoxmToInitState(); - RestorePstatToInitState(); + */ + if(gDoxm) + { + if(!gDoxm->owned && previousMsgId != ehRequest->messageID) + { + OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\ + "DOXM will be reverted."); + RestoreDoxmToInitState(); + RestorePstatToInitState(); + } + } + else + { + OIC_LOG(ERROR, TAG, "Invalid DOXM resource."); + } } - - //Send payload to request originator - if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0)) + else { - ehRet = OC_EH_ERROR; - OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleDoxmPostRequest"); + previousMsgId = ehRequest->messageID; } + + //Send payload to request originator + ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ? + OC_EH_OK : OC_EH_ERROR; + DeleteDoxmBinData(newDoxm); return ehRet; @@ -845,13 +998,13 @@ OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag, ehRet = HandleDoxmGetRequest(ehRequest); break; - case OC_REST_PUT: - ehRet = HandleDoxmPutRequest(ehRequest); + case OC_REST_POST: + ehRet = HandleDoxmPostRequest(ehRequest); break; default: - ehRet = OC_EH_ERROR; - SendSRMResponse(ehRequest, ehRet, NULL, 0); + ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ? + OC_EH_OK : OC_EH_ERROR; break; } } @@ -863,12 +1016,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) { diff --git a/resource/csdk/security/src/dpairingresource.c b/resource/csdk/security/src/dpairingresource.c index 0c5c03f87..9fc0ce7fd 100644 --- a/resource/csdk/security/src/dpairingresource.c +++ b/resource/csdk/security/src/dpairingresource.c @@ -136,7 +136,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 +297,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 +308,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"); @@ -476,7 +476,7 @@ static OCEntityHandlerResult HandleDpairingPostRequest (const OCEntityHandlerReq // should be lock /oic/sec/dpairing resource if Direct-Pairing starts normally ? OIC_LOG (DEBUG, TAG, "/oic/sec/dpairing resource created"); - ehRet = OC_EH_RESOURCE_CREATED; + ehRet = OC_EH_CHANGED; } else { @@ -559,24 +559,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 +717,7 @@ OCStackResult CreateDpairingResource() ret = OCCreateResource(&gDpairHandle, OIC_RSRC_TYPE_SEC_DPAIRING, - OIC_MI_DEF, + OC_RSRVD_INTERFACE_DEFAULT, OIC_RSRC_DPAIRING_URI, DpairingEntityHandler, NULL, diff --git a/resource/csdk/security/src/pconfresource.c b/resource/csdk/security/src/pconfresource.c index 921b249e5..239bc4b96 100644 --- a/resource/csdk/security/src/pconfresource.c +++ b/resource/csdk/security/src/pconfresource.c @@ -476,7 +476,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 +487,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 +505,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 +514,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 +546,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 +557,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 +576,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 +640,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 +661,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 +673,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 +684,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 +726,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 +737,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 +751,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 +762,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); @@ -938,7 +939,7 @@ static OCEntityHandlerResult HandlePconfPostRequest (const OCEntityHandlerReques // Update storage if(OC_EH_ERROR != ehRet && true == UpdatePersistentStorage(gPconf)) { - ehRet = OC_EH_RESOURCE_CREATED; + ehRet = OC_EH_CHANGED; } DeletePconfBinData(newPconf); @@ -1010,7 +1011,7 @@ OCStackResult CreatePconfResource() ret = OCCreateResource(&gPconfHandle, OIC_RSRC_TYPE_SEC_PCONF, - OIC_MI_DEF, + OC_RSRVD_INTERFACE_DEFAULT, OIC_RSRC_PCONF_URI, PconfEntityHandler, NULL, diff --git a/resource/csdk/security/src/policyengine.c b/resource/csdk/security/src/policyengine.c index 04f0fc3c5..ef57307d5 100644 --- a/resource/csdk/security/src/policyengine.c +++ b/resource/csdk/security/src/policyengine.c @@ -19,6 +19,7 @@ //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #include <string.h> +#include "utlist.h" #include "oic_malloc.h" #include "policyengine.h" #include "amsmgr.h" @@ -102,9 +103,15 @@ void SetPolicyEngineState(PEContext_t *context, const PEState_t state) context->amsProcessing = false; context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR; - FreeCARequestInfo(context->amsMgrContext->requestInfo); - OICFree(context->amsMgrContext->endpoint); - memset(context->amsMgrContext, 0, sizeof(AmsMgrContext_t)); + if (context->amsMgrContext) + { + if (context->amsMgrContext->requestInfo) + { + FreeCARequestInfo(context->amsMgrContext->requestInfo); + } + OICFree(context->amsMgrContext->endpoint); + memset(context->amsMgrContext, 0, sizeof(AmsMgrContext_t)); + } // Set state. context->state = state; @@ -125,11 +132,19 @@ static bool IsRequestFromDevOwner(PEContext_t *context) return retVal; } + /* if(OC_STACK_OK == GetDoxmDevOwnerId(&ownerid)) { retVal = UuidCmp(&context->subject, &ownerid); } + */ + // TODO: Added as workaround for CTT + OicSecDoxm_t* doxm = (OicSecDoxm_t*) GetDoxmResourceData(); + if (doxm) + { + retVal = UuidCmp(&doxm->owner, &context->subject); + } return retVal; } @@ -302,28 +317,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"); @@ -335,24 +354,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; } @@ -375,8 +395,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; @@ -385,28 +405,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; } @@ -417,7 +437,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)) { @@ -470,7 +490,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); diff --git a/resource/csdk/security/src/psinterface.c b/resource/csdk/security/src/psinterface.c index c10b097e1..9b0080b58 100644 --- a/resource/csdk/security/src/psinterface.c +++ b/resource/csdk/security/src/psinterface.c @@ -36,6 +36,8 @@ #include "secureresourcemanager.h" #include "srmresourcestrings.h" #include "srmutility.h" +#include "pstatresource.h" +#include "doxmresource.h" #define TAG "SRM-PSI" @@ -176,6 +178,7 @@ OCStackResult UpdateSecureResourceInPS(const char *rsrcName, const uint8_t *psPa uint8_t *svcCbor = NULL; uint8_t *credCbor = NULL; uint8_t *pconfCbor = NULL; + uint8_t *resetPfCbor = NULL; int64_t cborEncoderResult = CborNoError; OCStackResult ret = GetSecureVirtualDatabaseFromPS(NULL, &dbData, &dbSize); @@ -188,6 +191,7 @@ OCStackResult UpdateSecureResourceInPS(const char *rsrcName, const uint8_t *psPa size_t svcCborLen = 0; size_t credCborLen = 0; size_t pconfCborLen = 0; + size_t resetPfCborLen = 0; // Gets each secure virtual resource from persistent storage // this local scoping intended, for destroying large cbor instances after use @@ -240,13 +244,20 @@ OCStackResult UpdateSecureResourceInPS(const char *rsrcName, const uint8_t *psPa cborFindResult = cbor_value_dup_byte_string(&curVal, &pconfCbor, &pconfCborLen, NULL); VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PCONF Name Value."); } + cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_RESET_PF_NAME, &curVal); + if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal)) + { + cborFindResult = cbor_value_dup_byte_string(&curVal, &resetPfCbor, &resetPfCborLen, NULL); + VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Reset Profile Name Value."); + } } // Updates the added |psPayload| with the existing secure virtual resource(s) // this local scoping intended, for destroying large cbor instances after use { size_t size = aclCborLen + pstatCborLen + doxmCborLen + amaclCborLen - + svcCborLen + credCborLen + pconfCborLen + psSize + 255; + + svcCborLen + credCborLen + pconfCborLen + resetPfCborLen + + psSize + 255; // This added '255' is arbitrary value that is added to cover the name of the resource, map addition and ending outPayload = (uint8_t *) OICCalloc(1, size); @@ -313,6 +324,13 @@ OCStackResult UpdateSecureResourceInPS(const char *rsrcName, const uint8_t *psPa cborEncoderResult |= cbor_encode_byte_string(&secRsrc, pconfCbor, pconfCborLen); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pconf Value."); } + if (strcmp(OIC_JSON_RESET_PF_NAME, rsrcName) && resetPfCborLen) + { + cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_RESET_PF_NAME, strlen(OIC_JSON_RESET_PF_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Reset Profile Name."); + cborEncoderResult |= cbor_encode_byte_string(&secRsrc, resetPfCbor, resetPfCborLen); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Reset Profile Value."); + } cborEncoderResult |= cbor_encoder_close_container(&encoder, &secRsrc); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Array."); @@ -344,7 +362,7 @@ OCStackResult UpdateSecureResourceInPS(const char *rsrcName, const uint8_t *psPa if (outPayload && outSize) { - OIC_LOG_V(DEBUG, TAG, "Writting in the file: %zu", outSize); + OIC_LOG_V(DEBUG, TAG, "Writing in the file: %zu", outSize); OCPersistentStorage* ps = SRMGetPersistentStorageHandler(); if (ps) { @@ -382,5 +400,290 @@ exit: OICFree(svcCbor); OICFree(credCbor); OICFree(pconfCbor); + OICFree(resetPfCbor); + return ret; +} + +/** + * Resets the Secure Virtual Resource(s). + * This function reads the Reset Profile + * and resets the secure virtual resources accordingly. + * + * @return OCStackResult - result of updating Secure Virtual Resource(s) + */ +OCStackResult ResetSecureResourceInPS(void) +{ + OIC_LOG(DEBUG, TAG, "ResetSecureResourceInPS IN"); + + size_t dbSize = 0; + size_t outSize = 0; + uint8_t *dbData = NULL; + uint8_t *outPayload = NULL; + + uint8_t *aclCbor = NULL; + uint8_t *pstatCbor = NULL; + uint8_t *doxmCbor = NULL; + uint8_t *resetPfCbor = NULL; + + int64_t cborEncoderResult = CborNoError; + OCStackResult ret = GetSecureVirtualDatabaseFromPS(NULL, &dbData, &dbSize); + + if(dbData && dbSize) + { + size_t aclCborLen = 0; + size_t pstatCborLen = 0; + size_t doxmCborLen = 0; + size_t resetPfCborLen = 0; + + // Gets the reset profile from persistent storage + { + CborParser parser; // will be initialized in |cbor_parser_init| + CborValue cbor; // will be initialized in |cbor_parser_init| + cbor_parser_init(dbData, dbSize, 0, &parser, &cbor); + CborValue curVal = {0}; + CborError cborFindResult = CborNoError; + cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_RESET_PF_NAME, &curVal); + if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal)) + { + cborFindResult = cbor_value_dup_byte_string(&curVal, &resetPfCbor, &resetPfCborLen, NULL); + VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Reset Profile Name Value."); + } + } + + // Gets each secure virtual resource from the reset profile + { + CborParser parser; // will be initialized in |cbor_parser_init| + CborValue cbor; // will be initialized in |cbor_parser_init| + cbor_parser_init(resetPfCbor, resetPfCborLen, 0, &parser, &cbor); + CborValue curVal = {0}; + CborError cborFindResult = CborNoError; + cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_ACL_NAME, &curVal); + if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal)) + { + cborFindResult = cbor_value_dup_byte_string(&curVal, &aclCbor, &aclCborLen, NULL); + VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ACL Name Value."); + } + cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_PSTAT_NAME, &curVal); + if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal)) + { + cborFindResult = cbor_value_dup_byte_string(&curVal, &pstatCbor, &pstatCborLen, NULL); + VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PSTAT Name Value."); + } + cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_DOXM_NAME, &curVal); + if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal)) + { + cborFindResult = cbor_value_dup_byte_string(&curVal, &doxmCbor, &doxmCborLen, NULL); + VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DOXM Name Value."); + } + } + + { + size_t size = aclCborLen + pstatCborLen + doxmCborLen + resetPfCborLen + 255; + // This added '255' is arbitrary value added to cover the name of the resource, map addition, and ending + + outPayload = (uint8_t *) OICCalloc(1, size); + VERIFY_NON_NULL(TAG, outPayload, ERROR); + CborEncoder encoder; + cbor_encoder_init(&encoder, outPayload, size, 0); + CborEncoder secRsrc; + cborEncoderResult |= cbor_encoder_create_map(&encoder, &secRsrc, CborIndefiniteLength); + + cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_ACL_NAME, strlen(OIC_JSON_ACL_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Name."); + cborEncoderResult |= cbor_encode_byte_string(&secRsrc, aclCbor, aclCborLen); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Value."); + + cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_PSTAT_NAME, strlen(OIC_JSON_PSTAT_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Name."); + cborEncoderResult |= cbor_encode_byte_string(&secRsrc, pstatCbor, pstatCborLen); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Value."); + + cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_DOXM_NAME, strlen(OIC_JSON_DOXM_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DOXM Name."); + cborEncoderResult |= cbor_encode_byte_string(&secRsrc, doxmCbor, doxmCborLen); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DOXM Value."); + + cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_RESET_PF_NAME, strlen(OIC_JSON_RESET_PF_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Reset Profile Name."); + cborEncoderResult |= cbor_encode_byte_string(&secRsrc, resetPfCbor, resetPfCborLen); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Reset Profile Value."); + + cborEncoderResult |= cbor_encoder_close_container(&encoder, &secRsrc); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Array."); + outSize = encoder.ptr - outPayload; + } + + if (outPayload && outSize) + { + OIC_LOG_V(DEBUG, TAG, "Writing in the file: %zu", outSize); + OCPersistentStorage *ps = SRMGetPersistentStorageHandler(); + if (ps) + { + FILE *fp = ps->open(SVR_DB_DAT_FILE_NAME, "wb"); + if (fp) + { + size_t numberItems = ps->write(outPayload, 1, outSize, fp); + if (outSize == numberItems) + { + OIC_LOG_V(DEBUG, TAG, "Written %zu bytes into SVR database file", outSize); + ret= OC_STACK_OK; + } + else + { + OIC_LOG_V(ERROR, TAG, "Failed writing %zu in the database", numberItems); + } + ps->close(fp); + } + else + { + OIC_LOG(ERROR, TAG, "File open failed."); + } + + } + } + } + + SRMDeInitSecureResources(); + InitSecureResources(); + OIC_LOG(DEBUG, TAG, "ResetSecureResourceINPS OUT"); + +exit: + OICFree(dbData); + OICFree(outPayload); + OICFree(aclCbor); + OICFree(pstatCbor); + OICFree(doxmCbor); + OICFree(resetPfCbor); +} + +/** + * Creates Reset Profile from the initial secure virtual resources. + * This function copies the secure resources + * and creates the Reset Profile in the Persistent Storage. + * Device ID in doxm and pstat are left empty as it will be renewed after reset. + * + * @return OCStackResult - result of updating Secure Virtual Resource(s) + */ +OCStackResult CreateResetProfile(void) +{ + OIC_LOG(DEBUG, TAG, "CreateResetProfile IN"); + + size_t dbSize = 0; + uint8_t *dbData = NULL; + + uint8_t *aclCbor = NULL; + uint8_t *pstatCbor = NULL; + uint8_t *doxmCbor = NULL; + uint8_t *resetPfCbor = NULL; + + OCStackResult ret = OC_STACK_ERROR; + int64_t cborEncoderResult = CborNoError; + ret = GetSecureVirtualDatabaseFromPS(NULL, &dbData, &dbSize); + if (dbData && dbSize) + { + size_t aclCborLen = 0; + size_t pstatCborLen = 0; + size_t doxmCborLen = 0; + size_t resetPfCborLen = 0; + + { + CborParser parser; + CborValue cbor; + cbor_parser_init(dbData, dbSize, 0, &parser, &cbor); + CborValue curVal = {0}; + CborError cborFindResult = CborNoError; + cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_ACL_NAME, &curVal); + if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal)) + { + cborFindResult = cbor_value_dup_byte_string(&curVal, &aclCbor, &aclCborLen, NULL); + VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ACL Name Value."); + } + cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_PSTAT_NAME, &curVal); + if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal)) + { + cborFindResult = cbor_value_dup_byte_string(&curVal, &pstatCbor, &pstatCborLen, NULL); + VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PSTAT Name Value."); + } + cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_DOXM_NAME, &curVal); + if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal)) + { + cborFindResult = cbor_value_dup_byte_string(&curVal, &doxmCbor, &doxmCborLen, NULL); + VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DOXM Name Value."); + } + } + + // Set the Device ID in doxm and pstat to empty + if (pstatCbor) + { + OicSecPstat_t *pstat = NULL; + ret = CBORPayloadToPstat(pstatCbor, pstatCborLen, &pstat); + OICFree(pstatCbor); + pstatCbor = NULL; + pstatCborLen = 0; + + OicUuid_t emptyUuid = {.id = {0} }; + memcpy(&pstat->deviceID, &emptyUuid, sizeof(OicUuid_t)); + memcpy(&pstat->rownerID, &emptyUuid, sizeof(OicUuid_t)); + + ret = PstatToCBORPayload(pstat, &pstatCbor, &pstatCborLen, false); + OICFree(pstat); + } + if (doxmCbor) + { + OicSecDoxm_t *doxm = NULL; + ret = CBORPayloadToDoxm(doxmCbor, doxmCborLen, &doxm); + OICFree(doxmCbor); + doxmCbor = NULL; + doxmCborLen = 0; + + OicUuid_t emptyUuid = {.id = {0} }; + memcpy(&doxm->deviceID, &emptyUuid, sizeof(OicUuid_t)); + memcpy(&doxm->rownerID, &emptyUuid, sizeof(OicUuid_t)); + + ret = DoxmToCBORPayload(doxm, &doxmCbor, &doxmCborLen, false); + OICFree(doxm); + } + + { + size_t size = aclCborLen + pstatCborLen + doxmCborLen + 255; + resetPfCbor = (uint8_t *) OICCalloc(1, size); + VERIFY_NON_NULL(TAG, resetPfCbor, ERROR); + CborEncoder encoder; // will be initialized in |cbor_parser_init| + cbor_encoder_init(&encoder, resetPfCbor, size, 0); + CborEncoder secRsrc; // will be initialized in |cbor_encoder_create_map| + cborEncoderResult |= cbor_encoder_create_map(&encoder, &secRsrc, CborIndefiniteLength); + + cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_ACL_NAME, strlen(OIC_JSON_ACL_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Name."); + cborEncoderResult |= cbor_encode_byte_string(&secRsrc, aclCbor, aclCborLen); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Value."); + + cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_PSTAT_NAME, strlen(OIC_JSON_PSTAT_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Name."); + cborEncoderResult |= cbor_encode_byte_string(&secRsrc, pstatCbor, pstatCborLen); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Value."); + + cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_DOXM_NAME, strlen(OIC_JSON_DOXM_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Name."); + cborEncoderResult |= cbor_encode_byte_string(&secRsrc, doxmCbor, doxmCborLen); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Value."); + + cborEncoderResult |= cbor_encoder_close_container(&encoder, &secRsrc); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Array."); + resetPfCborLen = encoder.ptr - resetPfCbor; + } + + UpdateSecureResourceInPS(OIC_JSON_RESET_PF_NAME, resetPfCbor, resetPfCborLen); + + } + OIC_LOG(DEBUG, TAG, "CreateResetProfile OUT"); + +exit: + OICFree(dbData); + OICFree(aclCbor); + OICFree(pstatCbor); + OICFree(doxmCbor); + OICFree(resetPfCbor); return ret; } + diff --git a/resource/csdk/security/src/pstatresource.c b/resource/csdk/security/src/pstatresource.c index b3e63ac5c..1846d48f6 100644 --- a/resource/csdk/security/src/pstatresource.c +++ b/resource/csdk/security/src/pstatresource.c @@ -42,7 +42,10 @@ 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 = 6; + +// Number of writeable property +static const uint8_t WRITEABLE_PROPERTY_SIZE = 3; static OicSecDpom_t gSm = SINGLE_SERVICE_CLIENT_DRIVEN; static OicSecPstat_t gDefaultPstat = @@ -64,6 +67,14 @@ static OicSecPstat_t *gPstat = NULL; static OCResourceHandle gPstatHandle = NULL; +/** + * This method is internal method. + * the param roParsed is optionally used to know whether cborPayload has + * at least read only property value or not. + */ +static OCStackResult CBORPayloadToPstatBin(const uint8_t *cborPayload, const size_t size, + OicSecPstat_t **secPstat, bool *roParsed); + void DeletePstatBinData(OicSecPstat_t* pstat) { if (pstat) @@ -76,7 +87,8 @@ void DeletePstatBinData(OicSecPstat_t* pstat) } } -OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **payload, size_t *size) +OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **payload, size_t *size, + bool writableOnly) { if (NULL == pstat || NULL == payload || NULL != *payload || NULL == size) { @@ -93,7 +105,7 @@ OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **payload, *size = 0; OCStackResult ret = OC_STACK_ERROR; - + size_t pstatMapSize = PSTAT_MAP_SIZE; CborEncoder encoder; CborEncoder pstatMap; char* strUuid = NULL; @@ -104,7 +116,12 @@ OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **payload, VERIFY_NON_NULL(TAG, outPayload, ERROR); cbor_encoder_init(&encoder, outPayload, cborLen, 0); - cborEncoderResult = cbor_encoder_create_map(&encoder, &pstatMap, PSTAT_MAP_SIZE); + if (false == writableOnly) + { + pstatMapSize += WRITEABLE_PROPERTY_SIZE; + } + + cborEncoderResult = cbor_encoder_create_map(&encoder, &pstatMap, pstatMapSize); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pstat Map."); cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_ISOP_NAME, @@ -113,16 +130,6 @@ OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **payload, cborEncoderResult = cbor_encode_boolean(&pstatMap, pstat->isOp); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ISOP Name Value."); - cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_DEVICE_ID_NAME, - strlen(OIC_JSON_DEVICE_ID_NAME)); - VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag."); - ret = ConvertUuidToStr(&pstat->deviceID, &strUuid); - VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR); - cborEncoderResult = cbor_encode_text_string(&pstatMap, strUuid, strlen(strUuid)); - VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value."); - OICFree(strUuid); - strUuid = NULL; - cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_CM_NAME, strlen(OIC_JSON_CM_NAME)); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CM Name Tag."); @@ -141,21 +148,66 @@ OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **payload, cborEncoderResult = cbor_encode_int(&pstatMap, pstat->om); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding OM Name Value."); - cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_SM_NAME, - strlen(OIC_JSON_SM_NAME)); - VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SM Name Tag."); - cborEncoderResult = cbor_encode_int(&pstatMap, pstat->sm[0]); - VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SM Name Value."); - - cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_ROWNERID_NAME, - strlen(OIC_JSON_ROWNERID_NAME)); - VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag."); - ret = ConvertUuidToStr(&pstat->rownerID, &strUuid); - VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR); - cborEncoderResult = cbor_encode_text_string(&pstatMap, strUuid, strlen(strUuid)); - VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value."); - OICFree(strUuid); - strUuid = NULL; + if (false == writableOnly) + { + cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_SM_NAME, + strlen(OIC_JSON_SM_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SM Name Tag."); + cborEncoderResult = cbor_encode_int(&pstatMap, pstat->sm[0]); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SM Name Value."); + + cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_DEVICE_ID_NAME, + strlen(OIC_JSON_DEVICE_ID_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag."); + ret = ConvertUuidToStr(&pstat->deviceID, &strUuid); + VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR); + cborEncoderResult = cbor_encode_text_string(&pstatMap, strUuid, strlen(strUuid)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value."); + OICFree(strUuid); + strUuid = NULL; + + cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_ROWNERID_NAME, + strlen(OIC_JSON_ROWNERID_NAME)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag."); + ret = ConvertUuidToStr(&pstat->rownerID, &strUuid); + VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR); + cborEncoderResult = cbor_encode_text_string(&pstatMap, strUuid, strlen(strUuid)); + VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value."); + 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."); @@ -174,7 +226,7 @@ exit: // Since the allocated initial memory failed, double the memory. cborLen += encoder.ptr - encoder.end; cborEncoderResult = CborNoError; - ret = PstatToCBORPayload(pstat, payload, &cborLen); + ret = PstatToCBORPayload(pstat, payload, &cborLen, writableOnly); if (OC_STACK_OK == ret) { *size = cborLen; @@ -196,6 +248,12 @@ exit: OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t size, OicSecPstat_t **secPstat) { + return CBORPayloadToPstatBin(cborPayload, size, secPstat, NULL); +} + +static OCStackResult CBORPayloadToPstatBin(const uint8_t *cborPayload, const size_t size, + OicSecPstat_t **secPstat, bool *roParsed) +{ if (NULL == cborPayload || NULL == secPstat || NULL != *secPstat || 0 == size) { return OC_STACK_INVALID_PARAM; @@ -226,6 +284,11 @@ OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t size, cborFindResult = cbor_value_get_boolean(&pstatMap, &pstat->isOp); VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding isOp Value."); } + else + { + pstat->isOp = gPstat->isOp; + cborFindResult = CborNoError; + } cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_DEVICE_ID_NAME, &pstatMap); if (CborNoError == cborFindResult && cbor_value_is_text_string(&pstatMap)) @@ -236,6 +299,16 @@ OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t size, VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR); OICFree(strUuid ); strUuid = NULL; + + if (roParsed) + { + *roParsed = true; + } + } + else + { + memcpy(&pstat->deviceID, &gPstat->deviceID, sizeof(OicUuid_t)); + cborFindResult = CborNoError; } cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_CM_NAME, &pstatMap); @@ -244,6 +317,11 @@ OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t size, cborFindResult = cbor_value_get_int(&pstatMap, (int *) &pstat->cm); VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CM."); } + else + { + pstat->cm = gPstat->cm; + cborFindResult = CborNoError; + } cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_TM_NAME, &pstatMap); if (CborNoError == cborFindResult && cbor_value_is_integer(&pstatMap)) @@ -251,6 +329,11 @@ OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t size, cborFindResult = cbor_value_get_int(&pstatMap, (int *) &pstat->tm); VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding TM."); } + else + { + pstat->tm = gPstat->tm; + cborFindResult = CborNoError; + } cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_OM_NAME, &pstatMap); if (CborNoError == cborFindResult && cbor_value_is_integer(&pstatMap)) @@ -258,6 +341,11 @@ OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t size, cborFindResult = cbor_value_get_int(&pstatMap, (int *) &pstat->om); VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding OM."); } + else + { + pstat->om = gPstat->om; + cborFindResult = CborNoError; + } cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_SM_NAME, &pstatMap); if (CborNoError == cborFindResult && cbor_value_is_integer(&pstatMap)) @@ -267,6 +355,18 @@ OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t size, cborFindResult = cbor_value_get_int(&pstatMap, (int *) &pstat->sm[0]); VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SM."); + if (roParsed) + { + *roParsed = true; + } + } + else + { + VERIFY_NON_NULL(TAG, gPstat, ERROR); + pstat->smLen = gPstat->smLen; + pstat->sm = (OicSecDpom_t*)OICCalloc(pstat->smLen, sizeof(OicSecDpom_t)); + *pstat->sm = *gPstat->sm; + cborFindResult = CborNoError; } cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_ROWNERID_NAME, &pstatMap); @@ -278,6 +378,17 @@ OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t size, VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR); OICFree(strUuid ); strUuid = NULL; + + if (roParsed) + { + *roParsed = true; + } + } + else + { + VERIFY_NON_NULL(TAG, gPstat, ERROR); + memcpy(pstat->rownerID.id, gPstat->rownerID.id, sizeof(gPstat->rownerID.id)); + cborFindResult = CborNoError; } *secPstat = pstat; @@ -305,7 +416,7 @@ static bool UpdatePersistentStorage(OicSecPstat_t *pstat) size_t size = 0; uint8_t *cborPayload = NULL; - OCStackResult ret = PstatToCBORPayload(pstat, &cborPayload, &size); + OCStackResult ret = PstatToCBORPayload(pstat, &cborPayload, &size, false); if (OC_STACK_OK == ret) { if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_PSTAT_NAME, cborPayload, size)) @@ -318,28 +429,74 @@ 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; - - // Send response payload to request originator - if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, payload, size)) + if (ehRet == OC_EH_OK) { - ehRet = OC_EH_ERROR; - OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandlePstatGetRequest"); + if(OC_STACK_OK != PstatToCBORPayload(gPstat, &payload, &size, false)) + { + OIC_LOG(WARNING, TAG, "PstatToCBORPayload failed in HandlePstatGetRequest"); + } } + + // Send response payload to request originator + ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ? + OC_EH_OK : OC_EH_ERROR; OICFree(payload); return ehRet; } @@ -350,75 +507,150 @@ 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; + static uint16_t prevMsgId = 0; - if (ehRequest->payload) + if (ehRequest->payload && NULL != gPstat) { uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData; size_t size = ((OCSecurityPayload *) ehRequest->payload)->payloadSize; VERIFY_NON_NULL(TAG, payload, ERROR); - OCStackResult ret = CBORPayloadToPstat(payload, size, &pstat); + bool roParsed = false; + OCStackResult ret = CBORPayloadToPstatBin(payload, size, &pstat, &roParsed); VERIFY_NON_NULL(TAG, pstat, ERROR); if (OC_STACK_OK == ret) { - if (false == (pstat->cm & TAKE_OWNER) && false == pstat->isOp) + bool validReq = false; + + if (true == roParsed) { - gPstat->cm = pstat->cm; - OIC_LOG (INFO, TAG, "State changed to Ready for Provisioning"); + OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only properties"); + ehRet = OC_EH_NOT_ACCEPTABLE; + goto exit; } - else if (false == (pstat->cm & TAKE_OWNER) && true == pstat->isOp) + + //operation mode(om) should be one of supported modes(sm) + for(size_t i = 0; i < gPstat->smLen; i++) { - gPstat->isOp =pstat->isOp; - OIC_LOG (INFO, TAG, "State changed to Ready for Normal Operation"); + if(gPstat->sm[i] == pstat->om) + { + validReq = true; + break; + } } - else + + if(!validReq) { - OIC_LOG(DEBUG, TAG, "Invalid Device provisionig state"); + OIC_LOG_V(ERROR, TAG, "%d is unsupported Operation Mode", (int) pstat->om); + ehRet = OC_EH_BAD_REQ; + goto exit; } - if (pstat->om != MULTIPLE_SERVICE_SERVER_DRIVEN && gPstat) + validReq = false; + + //Currently, we dose not support the multiple service server driven yet. + if (pstat->om != MULTIPLE_SERVICE_SERVER_DRIVEN) { - /* - * Check if the operation mode is in the supported provisioning services - * operation mode list. - */ - for (size_t i=0; i< gPstat->smLen; i++) + if ((pstat->cm & RESET) && false == pstat->isOp) + { + validReq = true; + OIC_LOG(INFO, TAG, "State changed to Ready for Reset"); + } + else if ((pstat->cm & TAKE_OWNER) && false == pstat->isOp) { - if(gPstat->sm[i] == pstat->om) - { - gPstat->om = pstat->om; - break; - } + validReq = true; + OIC_LOG (INFO, TAG, "State changed to Ready for Ownership transfer"); + } + else if (false == (pstat->cm & TAKE_OWNER) && false == pstat->isOp) + { + validReq = true; + OIC_LOG(INFO, TAG, "State changed to Ready for Provisioning"); + } + else if (false == (pstat->cm & TAKE_OWNER) && true == pstat->isOp) + { + validReq = true; + OIC_LOG (INFO, TAG, "State changed to Ready for Normal Operation"); + } + else + { + OIC_LOG(DEBUG, TAG, "Invalid Device provisionig state"); + OIC_LOG_BUFFER(DEBUG, TAG, payload, size); + ehRet = OC_EH_BAD_REQ; + goto exit; } } + + if (!validReq) + { + OIC_LOG(DEBUG, TAG, "Bad request for PSTAT"); + ehRet = OC_EH_BAD_REQ; + goto exit; + } + + gPstat->isOp = pstat->isOp; + gPstat->om = pstat->om; + gPstat->tm = pstat->tm; + gPstat->cm = pstat->cm; + // Convert pstat data into CBOR for update to persistent storage if (UpdatePersistentStorage(gPstat)) { ehRet = OC_EH_OK; } + if (true == (pstat->cm & RESET)) + { + if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0)) + { + ehRet = OC_EH_ERROR; + OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandlePstatPostRequest"); + DeletePstatBinData(pstat); + return ehRet; + } + ret = ResetSecureResourceInPS(); + if (OC_STACK_OK == ret) + { + ehRet = OC_EH_OK; + } + DeletePstatBinData(pstat); + return ehRet; + } } } exit: - if(OC_EH_OK != ehRet) - { - /* - * If some error is occured while ownership transfer, - * ownership transfer related resource should be revert back to initial status. - */ - RestoreDoxmToInitState(); - RestorePstatToInitState(); - } - //Send payload to request originator - if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0)) - { - ehRet = OC_EH_ERROR; - OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandlePstatPostRequest"); - } + if(OC_EH_OK != ehRet) + { + /* + * If some error is occured while ownership transfer, + * ownership transfer related resource should be revert back to initial status. + */ + const OicSecDoxm_t* doxm = GetDoxmResourceData(); + if(doxm) + { + if(!doxm->owned && prevMsgId != ehRequest->messageID) + { + RestoreDoxmToInitState(); + RestorePstatToInitState(); + } + } + else + { + OIC_LOG(ERROR, TAG, "Invalid DOXM resource."); + } + } + else + { + prevMsgId = ehRequest->messageID; + } + + // Send response payload to request originator + ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ? + OC_EH_OK : OC_EH_ERROR; + DeletePstatBinData(pstat); return ehRet; } @@ -441,12 +673,12 @@ 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; - SendSRMResponse(ehRequest, ehRet, NULL, 0); + ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ? + OC_EH_OK : OC_EH_ERROR; break; } } @@ -460,11 +692,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) { @@ -592,7 +825,7 @@ OCStackResult SetPstatRownerId(const OicUuid_t* newROwner) memcpy(prevId.id, gPstat->rownerID.id, sizeof(prevId.id)); memcpy(gPstat->rownerID.id, newROwner->id, sizeof(newROwner->id)); - ret = PstatToCBORPayload(gPstat, &cborPayload, &size); + ret = PstatToCBORPayload(gPstat, &cborPayload, &size, false); VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR); ret = UpdateSecureResourceInPS(OIC_JSON_PSTAT_NAME, cborPayload, size); diff --git a/resource/csdk/security/src/srmresourcestrings.c b/resource/csdk/security/src/srmresourcestrings.c index d7b3c77f4..d9f0210ce 100644 --- a/resource/csdk/security/src/srmresourcestrings.c +++ b/resource/csdk/security/src/srmresourcestrings.c @@ -20,69 +20,72 @@ #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"; +//reset profile +const char * OIC_JSON_RESET_PF_NAME = "resetpf"; + const char * OIC_JSON_SUBJECT_NAME = "subject"; const char * OIC_JSON_RESOURCES_NAME = "resources"; const char * OIC_JSON_AMSS_NAME = "amss"; @@ -115,12 +118,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.org.iotivity.dpc"; const char * OIC_JSON_EDP_NAME = "edp"; const char * OIC_JSON_PIN_NAME = "pin"; const char * OIC_JSON_PDACL_NAME = "pdacl"; @@ -130,10 +134,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"; diff --git a/resource/csdk/security/src/svcresource.c b/resource/csdk/security/src/svcresource.c index a1175aa87..410d22c2b 100644 --- a/resource/csdk/security/src/svcresource.c +++ b/resource/csdk/security/src/svcresource.c @@ -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); @@ -353,7 +353,7 @@ static OCEntityHandlerResult HandleSVCPostRequest(const OCEntityHandlerRequest * if (cborPayload && OC_STACK_OK == res && UpdateSecureResourceInPS(OIC_JSON_SVC_NAME, cborPayload, size) == OC_STACK_OK) { - ehRet = OC_EH_RESOURCE_CREATED; + ehRet = OC_EH_CHANGED; } OICFree(cborPayload); } @@ -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, diff --git a/resource/csdk/security/src/verresource.c b/resource/csdk/security/src/verresource.c index 0bd3f75c3..96afaccf9 100644 --- a/resource/csdk/security/src/verresource.c +++ b/resource/csdk/security/src/verresource.c @@ -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, diff --git a/resource/csdk/security/tool/json2cbor.c b/resource/csdk/security/tool/json2cbor.c index 09191cb60..864a36592 100644 --- a/resource/csdk/security/tool/json2cbor.c +++ b/resource/csdk/security/tool/json2cbor.c @@ -20,6 +20,7 @@ #include <stdlib.h> #include <string.h> +#include "utlist.h" #include "cJSON.h" #include "base64.h" #include "cainterface.h" @@ -140,7 +141,7 @@ static void ConvertJsonToCBOR(const char *jsonFileName, const char *cborFileName { OicSecPstat_t *pstat = JSONToPstatBin(jsonStr); VERIFY_NON_NULL(TAG, pstat, FATAL); - ret = PstatToCBORPayload(pstat, &pstatCbor, &pstatCborSize); + ret = PstatToCBORPayload(pstat, &pstatCbor, &pstatCborSize, false); if(OC_STACK_OK != ret) { OIC_LOG (ERROR, TAG, "Failed converting Pstat to Cbor Payload"); @@ -156,7 +157,7 @@ static void ConvertJsonToCBOR(const char *jsonFileName, const char *cborFileName { OicSecDoxm_t *doxm = JSONToDoxmBin(jsonStr); VERIFY_NON_NULL(TAG, doxm, FATAL); - ret = DoxmToCBORPayload(doxm, &doxmCbor, &doxmCborSize); + ret = DoxmToCBORPayload(doxm, &doxmCbor, &doxmCborSize, false); if(OC_STACK_OK != ret) { OIC_LOG (ERROR, TAG, "Failed converting Doxm to Cbor Payload"); @@ -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,15 +367,14 @@ 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); @@ -397,69 +384,116 @@ OicSecAcl_t* JSONToAclBin(const char * jsonStr) 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 +767,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 +824,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. diff --git a/resource/csdk/security/unittest/SConscript b/resource/csdk/security/unittest/SConscript index c431d77fa..c3d2e7276 100644 --- a/resource/csdk/security/unittest/SConscript +++ b/resource/csdk/security/unittest/SConscript @@ -17,14 +17,15 @@ # // limitations under the License. # // # //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -# -Import('env') import os import os.path -srmtest_env = env.Clone() +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +srmtest_env = gtest_env.Clone() src_dir = srmtest_env.get('SRC_DIR') +target_os = srmtest_env.get('TARGET_OS') ###################################################################### # Build flags @@ -42,17 +43,16 @@ srmtest_env.PrependUnique(CPPPATH = [ '../../stack/include', '../../stack/include/internal', '../../../oc_logger/include', - '../../../../extlibs/gtest/gtest-1.7.0/include', '../../../../extlibs/cjson/', '../provisioning/include', # '../../../../extlibs/tinydtls/', '../include' ]) -srmtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) -srmtest_env.AppendUnique(LIBS = ['-lpthread']) -srmtest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) -srmtest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs']) +if target_os not in ['windows']: + srmtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) + srmtest_env.AppendUnique(LIBS = ['pthread']) +srmtest_env.AppendUnique(LIBPATH = [srmtest_env.get('BUILD_DIR')]) srmtest_env.PrependUnique(LIBS = ['ocsrm', 'octbstack', 'oc_logger', @@ -61,10 +61,10 @@ srmtest_env.PrependUnique(LIBS = ['ocsrm', 'gtest', 'gtest_main']) -if env.get('SECURED') == '1': +if srmtest_env.get('SECURED') == '1': srmtest_env.AppendUnique(LIBS = ['tinydtls']) -if not env.get('RELEASE'): +if srmtest_env.get('LOGGING') == '1': srmtest_env.AppendUnique(CPPDEFINES = ['TB_LOG']) ###################################################################### @@ -82,14 +82,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_src_dir = os.path.join(src_dir, 'resource', 'csdk', 'security', 'unittest') + os.sep +unittest_build_dir = os.path.join(srmtest_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')) @@ -104,17 +105,18 @@ 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')) -env.AppendTarget('test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': - out_dir = env.get('BUILD_DIR') - result_dir = env.get('BUILD_DIR') + '/test_out/' +srmtest_env.AppendTarget('test') +if srmtest_env.get('TEST') == '1': + if target_os in ['linux']: + out_dir = srmtest_env.get('BUILD_DIR') + result_dir = os.path.join(srmtest_env.get('BUILD_DIR'), 'test_out') + os.sep 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('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') + srmtest_env.AppendENVPath('PATH', [os.path.join(out_dir, 'resource', 'csdk')]) + from tools.scons.RunTest import * + run_test(srmtest_env,'ut','resource/csdk/security/unittest/unittest') diff --git a/resource/csdk/security/unittest/aclresourcetest.cpp b/resource/csdk/security/unittest/aclresourcetest.cpp index 558406a69..6d90fe8ad 100644 --- a/resource/csdk/security/unittest/aclresourcetest.cpp +++ b/resource/csdk/security/unittest/aclresourcetest.cpp @@ -23,6 +23,7 @@ #include <grp.h> #include <linux/limits.h> #include <sys/stat.h> +#include "utlist.h" #include "ocstack.h" #include "psinterface.h" #include "ocpayload.h" @@ -52,42 +53,111 @@ 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 +166,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 +214,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 +259,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 +297,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 +322,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 +333,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 +360,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 +381,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 +429,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 +436,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 +450,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 +462,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 +484,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 +491,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 +515,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 +529,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 +551,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 +559,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); diff --git a/resource/csdk/security/unittest/credentialresource.cpp b/resource/csdk/security/unittest/credentialresource.cpp index fd63aa128..13fce8601 100644 --- a/resource/csdk/security/unittest/credentialresource.cpp +++ b/resource/csdk/security/unittest/credentialresource.cpp @@ -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 index 000000000..d7c17efa8 --- /dev/null +++ b/resource/csdk/security/unittest/crlresourcetest.cpp @@ -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 diff --git a/resource/csdk/security/unittest/directpairingtest.cpp b/resource/csdk/security/unittest/directpairingtest.cpp index 5c49a2181..4904b35ff 100644 --- a/resource/csdk/security/unittest/directpairingtest.cpp +++ b/resource/csdk/security/unittest/directpairingtest.cpp @@ -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)); } diff --git a/resource/csdk/security/unittest/doxmresource.cpp b/resource/csdk/security/unittest/doxmresource.cpp index bdab37353..0fc7662be 100644 --- a/resource/csdk/security/unittest/doxmresource.cpp +++ b/resource/csdk/security/unittest/doxmresource.cpp @@ -143,10 +143,10 @@ TEST(DoxmResourceTest, DoxmToCBORPayloadNULL) OicSecDoxm_t *doxm = getBinDoxm(); size_t size = 10; uint8_t *payload = NULL; - EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(NULL, NULL, 0)); - EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(doxm, NULL, &size)); - EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(doxm, &payload, 0)); - EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(NULL, &payload, &size)); + EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(NULL, NULL, 0, false)); + EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(doxm, NULL, &size, false)); + EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(doxm, &payload, 0, false)); + EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(NULL, &payload, &size, false)); DeleteDoxmBinData(doxm); } @@ -156,7 +156,7 @@ TEST(DoxmResourceTest, DoxmToCBORPayloadVALID) uint8_t *payload = NULL; size_t size = 0; - EXPECT_EQ(OC_STACK_OK, DoxmToCBORPayload(doxm, &payload, &size)); + EXPECT_EQ(OC_STACK_OK, DoxmToCBORPayload(doxm, &payload, &size, false)); EXPECT_TRUE(payload != NULL); DeleteDoxmBinData(doxm); @@ -181,7 +181,7 @@ TEST(DoxmResourceTest, CBORPayloadToDoxmVALID) OicSecDoxm_t *doxm = getBinDoxm(); uint8_t *payload = NULL; size_t size = 0; - EXPECT_EQ(OC_STACK_OK, DoxmToCBORPayload(doxm, &payload, &size)); + EXPECT_EQ(OC_STACK_OK, DoxmToCBORPayload(doxm, &payload, &size, false)); EXPECT_TRUE(payload != NULL); OicSecDoxm_t *doxmSec = NULL; diff --git a/resource/csdk/security/unittest/oic_svr_db.dat b/resource/csdk/security/unittest/oic_svr_db.dat Binary files differindex c048b16a6..7758880d5 100644 --- a/resource/csdk/security/unittest/oic_svr_db.dat +++ b/resource/csdk/security/unittest/oic_svr_db.dat diff --git a/resource/csdk/security/unittest/oic_svr_db.json b/resource/csdk/security/unittest/oic_svr_db.json index 7c86ab382..31c276378 100644 --- a/resource/csdk/security/unittest/oic_svr_db.json +++ b/resource/csdk/security/unittest/oic_svr_db.json @@ -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 @@ -44,20 +32,20 @@ { "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 @@ -68,14 +56,14 @@ { "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 @@ -101,6 +89,6 @@ "deviceuuid": "756E6B6E-6F77-6564-4465-766963654964", "devowneruuid": "", "rowneruuid": "756E6B6E-6F77-6564-4465-766963654964", - "dpc": true + "x.org.iotivity.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 Binary files differnew file mode 100644 index 000000000..4b5604ef5 --- /dev/null +++ b/resource/csdk/security/unittest/oic_svr_db_prov.dat diff --git a/resource/csdk/security/unittest/oic_svr_db_prov.json b/resource/csdk/security/unittest/oic_svr_db_prov.json new file mode 100644 index 000000000..a24fd3bd9 --- /dev/null +++ b/resource/csdk/security/unittest/oic_svr_db_prov.json @@ -0,0 +1,109 @@ +{
+ "cred": {
+ "creds": [
+ {
+ "credid": 1,
+ "subjectuuid": "61646d69-6e44-6576-6963-655575696430",
+ "credtype": 1,
+ "privatedata": {
+
"data": "AAAAAAAAAAAAAAAA",
+ "encoding": "oic.sec.encoding.raw"
+ }
+ },
+ {
+ "credid": 2,
+ "subjectuuid": "646f6f72-4465-7669-6365-555549443030",
+ "credtype": 8,
+ "publicdata": {
+ "data": "AABBCCDDEEFFGGHH",
+ "encoding": "oic.sec.encoding.raw"
+ },
+ "privatedata": {
+ "data": "BBBBBBBBBBBBBBBB",
+ "encoding": "oic.sec.encoding.raw"
+ }
+ }
+ ],
+
"rowneruuid": "61646d69-6e44-6576-6963-655575696430"
+ },
+ "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"]
+ },
+ {
+ "href": "/oic/presence",
+ "rel": "",
+ "rt": ["oic.wk.presence"],
+ "if": ["oic.if.baseline"]
+ }
+ ],
+ "permission": 2
+ },
+ {
+ "subjectuuid": "*",
+ "resources": [
+ {
+ "href": "/oic/sec/doxm",
+ "rel": "",
+ "rt": ["oic.r.doxm"],
+ "if": ["oic.if.baseline"]
+ },
+ {
+ "href": "/oic/sec/pstat",
+ "rel": "",
+ "rt": ["oic.r.pstat"],
+ "if": ["oic.if.baseline"]
+ }
+ ],
+ "permission": 2
+ }
+ ]
+ },
+ "rowneruuid": "61646d69-6e44-6576-6963-655575696430"
+ },
+ "pstat": {
+ "isop": true,
+ "deviceuuid": "646f6f72-4465-7669-6365-555549443030",
+ "cm": 0,
+ "tm": 0,
+ "om": 3,
+ "sm": 3,
+ "rowneruuid": "61646d69-6e44-6576-6963-655575696430"
+ },
+ "doxm": {
+ "oxms": [0],
+ "oxmsel": 0,
+ "sct": 1,
+ "owned": true,
+ "deviceuuid": "646f6f72-4465-7669-6365-555549443030",
+ "devowneruuid": "61646d69-6e44-6576-6963-655575696430",
+ "rowneruuid": "61646d69-6e44-6576-6963-655575696430",
+ "x.org.iotivity.dpc": false
+ },
+ "pconf": {
+ "edp": false,
+ "pin": "00000000",
+ "deviceuuid": "646f6f72-4465-7669-6365-555549443030",
+ "rowneruuid": "61646d69-6e44-6576-6963-655575696430"
+ }
+}
\ No newline at end of file diff --git a/resource/csdk/security/unittest/oic_unittest.dat b/resource/csdk/security/unittest/oic_unittest.dat Binary files differindex e02289284..4befed00c 100644 --- a/resource/csdk/security/unittest/oic_unittest.dat +++ b/resource/csdk/security/unittest/oic_unittest.dat diff --git a/resource/csdk/security/unittest/oic_unittest.json b/resource/csdk/security/unittest/oic_unittest.json index 922be8693..c4357217d 100644 --- a/resource/csdk/security/unittest/oic_unittest.json +++ b/resource/csdk/security/unittest/oic_unittest.json @@ -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", @@ -26,17 +26,17 @@ { "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 } ] }, diff --git a/resource/csdk/security/unittest/oic_unittest_acl1.dat b/resource/csdk/security/unittest/oic_unittest_acl1.dat index 93c837035..9b915321f 100644 --- a/resource/csdk/security/unittest/oic_unittest_acl1.dat +++ b/resource/csdk/security/unittest/oic_unittest_acl1.dat @@ -1 +1 @@ -¿caclY‹¢faclist¡daces„£ksubjectuuida*iresources†¤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£ksubjectuuida*iresources‚¤dhrefm/oic/sec/doxmcrel`brt`bif`¤dhrefn/oic/sec/pstatcrel`brt`bif`jpermission£ksubjectuuidx$31313131-3131-3131-3131-313131313131iresources‚¤dhrefj/oic/lightcrel`brt`bif`¤dhrefh/oic/fancrel`brt`bif`jpermission£ksubjectuuidx$33333333-3333-3333-3333-333333333333iresources‚¤dhrefj/oic/lightcrel`brt`bif`¤dhrefk/oic/garagecrel`brt`bif`jpermissionjrowneruuidx$32323232-3232-3232-3232-323232323232ÿ
\ No newline at end of file +¿caclY ¢faclist¡daces„£ksubjectuuida*iresourcesƒ¤dhrefh/oic/resbrtjoic.wk.resbifioic.if.llcrel`¤dhreff/oic/dbrthoic.wk.dbif‚ooic.if.baselinehoic.if.rcrel`¤dhreff/oic/pbrthoic.wk.pbif‚ooic.if.baselinehoic.if.rcrel`jpermission£ksubjectuuida*iresources‚¤dhrefm/oic/sec/doxmbrtjoic.r.doxmbifooic.if.baselinecrel`¤dhrefn/oic/sec/pstatbrtkoic.r.pstatbifooic.if.baselinecrel`jpermission£ksubjectuuidx$31313131-3131-3131-3131-313131313131iresources‚¤dhrefj/oic/lightbrthoic.corebifooic.if.baselinecrel`¤dhrefh/oic/fanbrthoic.corebifooic.if.baselinecrel`jpermission£ksubjectuuidx$33333333-3333-3333-3333-333333333333iresources‚¤dhrefj/oic/lightbrthoic.corebifooic.if.baselinecrel`¤dhrefk/oic/garagebrthoic.corebifooic.if.baselinecrel`jpermissionjrowneruuidx$32323232-3232-3232-3232-323232323232ÿ
\ No newline at end of file diff --git a/resource/csdk/security/unittest/oic_unittest_acl1.json b/resource/csdk/security/unittest/oic_unittest_acl1.json index 7dd810f08..7dbb78b59 100644 --- a/resource/csdk/security/unittest/oic_unittest_acl1.json +++ b/resource/csdk/security/unittest/oic_unittest_acl1.json @@ -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 @@ -50,14 +32,14 @@ { "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 @@ -68,17 +50,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", @@ -86,17 +68,17 @@ { "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 } ] }, diff --git a/resource/csdk/security/unittest/oic_unittest_default_acl.dat b/resource/csdk/security/unittest/oic_unittest_default_acl.dat index e9efbb52e..064d997be 100644 --- a/resource/csdk/security/unittest/oic_unittest_default_acl.dat +++ b/resource/csdk/security/unittest/oic_unittest_default_acl.dat @@ -1 +1 @@ -¿caclYX¢faclist¡daces£ksubjectuuida*iresourcesˆ¤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`jpermissionjrowneruuidx$32323232-3232-3232-3232-323232323232ÿ
\ No newline at end of file +¿caclYâfaclist¡daces£ksubjectuuida*iresources†¤dhrefh/oic/resbrtjoic.wk.resbifioic.if.llcrel`¤dhreff/oic/dbrthoic.wk.dbif‚ooic.if.baselinehoic.if.rcrel`¤dhreff/oic/pbrthoic.wk.pbif‚ooic.if.baselinehoic.if.rcrel`¤dhrefm/oic/sec/doxmbrtjoic.r.doxmbifooic.if.baselinecrel`¤dhrefn/oic/sec/pstatbrtkoic.r.pstatbifooic.if.baselinecrel`¤dhrefl/oic/sec/aclbrtioic.r.aclbifooic.if.baselinecrel`jpermissionjrowneruuidx$32323232-3232-3232-3232-323232323232ÿ
\ No newline at end of file diff --git a/resource/csdk/security/unittest/oic_unittest_default_acl.json b/resource/csdk/security/unittest/oic_unittest_default_acl.json index d624da596..df8739a4c 100644 --- a/resource/csdk/security/unittest/oic_unittest_default_acl.json +++ b/resource/csdk/security/unittest/oic_unittest_default_acl.json @@ -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 diff --git a/resource/csdk/security/unittest/pstatresource.cpp b/resource/csdk/security/unittest/pstatresource.cpp index d1c93963d..08001ecc7 100644 --- a/resource/csdk/security/unittest/pstatresource.cpp +++ b/resource/csdk/security/unittest/pstatresource.cpp @@ -74,7 +74,7 @@ TEST(PstatResourceTest, PstatEntityHandlerWithPostRequest) defaultPstat->sm[0] = (OicSecDpom_t) 3; size_t size = 0; uint8_t *cbor = NULL; - EXPECT_EQ(OC_STACK_OK, PstatToCBORPayload(defaultPstat, &cbor, &size)); + EXPECT_EQ(OC_STACK_OK, PstatToCBORPayload(defaultPstat, &cbor, &size, true)); DeletePstatBinData(defaultPstat); ASSERT_TRUE(cbor != NULL); @@ -93,20 +93,20 @@ TEST(PstatResourceTest, PstatEntityHandlerInvalidRequest) TEST(PstatResourceTest, PstatToCBORPayloadNULL) { - EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(NULL, NULL, 0)); + EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(NULL, NULL, 0, false)); // Case when cbor payload is NULL OicSecPstat_t pstat; size_t size = 10; - EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, NULL, &size)); + EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, NULL, &size, false)); uint8_t *cborPayload = (uint8_t *) OICCalloc(1, size); ASSERT_TRUE(NULL != cborPayload); - EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, &cborPayload, &size)); + EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, &cborPayload, &size, false)); OICFree(cborPayload); cborPayload = NULL; // Case when pstat is zero. - EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(NULL, &cborPayload, &size)); + EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(NULL, &cborPayload, &size, false)); // Case when size is 0. - EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, &cborPayload, 0)); + EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, &cborPayload, 0, false)); OICFree(cborPayload); } @@ -133,7 +133,7 @@ TEST(PstatResourceTest, PstatToCBORPayloadAndCBORPayloadToPstat) size_t size = 0; uint8_t *cbor = NULL; - EXPECT_EQ(OC_STACK_OK, PstatToCBORPayload(&pstat, &cbor, &size)); + EXPECT_EQ(OC_STACK_OK, PstatToCBORPayload(&pstat, &cbor, &size, false)); if (!cbor) { OICFree(pstat.sm); diff --git a/resource/csdk/stack/include/internal/ocserverrequest.h b/resource/csdk/stack/include/internal/ocserverrequest.h index ee48b7e7b..d7f7bae8e 100644 --- a/resource/csdk/stack/include/internal/ocserverrequest.h +++ b/resource/csdk/stack/include/internal/ocserverrequest.h @@ -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 diff --git a/resource/csdk/stack/include/internal/ocstackinternal.h b/resource/csdk/stack/include/internal/ocstackinternal.h index bef3e9829..62115d62d 100644 --- a/resource/csdk/stack/include/internal/ocstackinternal.h +++ b/resource/csdk/stack/include/internal/ocstackinternal.h @@ -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 1*/ +#define OC_OFFSET_SEQUENCE_NUMBER (0) /** * 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. diff --git a/resource/csdk/stack/include/internal/oickeepalive.h b/resource/csdk/stack/include/internal/oickeepalive.h index c6a4d02cd..95f3cd05a 100644 --- a/resource/csdk/stack/include/internal/oickeepalive.h +++ b/resource/csdk/stack/include/internal/oickeepalive.h @@ -85,13 +85,7 @@ OCStackResult HandleKeepAliveRequest(const CAEndpoint_t* endPoint, * API to handle the connected device for KeepAlive. * @return Current Time. */ -void HandleKeepAliveConnCB(const CAEndpoint_t *endpoint); - -/** - * API to handle the disconnected device for KeepAlive. - * @return Current Time. - */ -void HandleKeepAliveDisconnCB(const CAEndpoint_t *endpoint); +void HandleKeepAliveConnCB(const CAEndpoint_t *endpoint, bool isConnected); #ifdef __cplusplus } // extern "C" diff --git a/resource/csdk/stack/include/ocpayload.h b/resource/csdk/stack/include/ocpayload.h index c8a7cfc3a..394425448 100644 --- a/resource/csdk/stack/include/ocpayload.h +++ b/resource/csdk/stack/include/ocpayload.h @@ -75,6 +75,7 @@ bool OCRepPayloadSetUri(OCRepPayload* payload, const char* uri); bool OCRepPayloadAddResourceType(OCRepPayload* payload, const char* resourceType); bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* interface); +bool OCRepPayloadAddModelVersion(OCRepPayload* payload, const char* dmv); bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceType); bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface); @@ -223,7 +224,7 @@ OCSecurityPayload* OCSecurityPayloadCreate(const uint8_t* securityData, size_t s void OCSecurityPayloadDestroy(OCSecurityPayload* payload); void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res, - uint16_t port); + uint16_t securePort, uint16_t tcpPort); void OCDiscoveryPayloadAddNewResource(OCDiscoveryPayload* payload, OCResourcePayload* res); bool OCResourcePayloadAddStringLL(OCStringLL **payload, const char* type); @@ -253,6 +254,22 @@ void OCPresencePayloadDestroy(OCPresencePayload* payload); OCStringLL* CloneOCStringLL (OCStringLL* ll); 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) + **/ +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) + **/ +char* OCCreateString(const OCStringLL* ll); + #ifdef __cplusplus } #endif diff --git a/resource/csdk/stack/include/ocstack.h b/resource/csdk/stack/include/ocstack.h index 9eeae7ec5..1733f118e 100644 --- a/resource/csdk/stack/include/ocstack.h +++ b/resource/csdk/stack/include/ocstack.h @@ -231,7 +231,13 @@ OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandle /** * 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. @@ -547,7 +553,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, +OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber, OCDirectPairingCB resultCallback); //#endif // DIRECT_PAIRING diff --git a/resource/csdk/stack/include/ocstackconfig.h b/resource/csdk/stack/include/ocstackconfig.h index 8680c7f46..f5ecebb09 100644 --- a/resource/csdk/stack/include/ocstackconfig.h +++ b/resource/csdk/stack/include/ocstackconfig.h @@ -39,7 +39,7 @@ * Maximum length of the query supported by client/server while processing * REST requests/responses. */ -#define MAX_QUERY_LENGTH (64) +#define MAX_QUERY_LENGTH (256) /** * Maximum length of the Manufacturer name supported by the server diff --git a/resource/csdk/stack/include/octypes.h b/resource/csdk/stack/include/octypes.h index c7bd0f991..a71e5c575 100644 --- a/resource/csdk/stack/include/octypes.h +++ b/resource/csdk/stack/include/octypes.h @@ -197,6 +197,9 @@ extern "C" { /** Port. */ #define OC_RSRVD_HOSTING_PORT "port" +/** TCP Port. */ +#define OC_RSRVD_TCP_PORT "x.org.iotivity.tcp" + /** For Server instance ID.*/ #define OC_RSRVD_SERVER_INSTANCE_ID "sid" @@ -374,14 +377,14 @@ typedef enum OC_FLAG_SECURE = (1 << 4), /** IPv4 & IPv6 auto-selection is the default.*/ - /** IP adapter only.*/ + /** IP & TCP adapter only.*/ OC_IP_USE_V6 = (1 << 5), - /** IP adapter only.*/ + /** 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.*/ @@ -575,11 +578,11 @@ typedef enum /** De-register observation, intended for internal use.*/ OC_REST_CANCEL_OBSERVE = (1 << 6), - #ifdef WITH_PRESENCE +#ifdef WITH_PRESENCE /** Subscribe for all presence notifications of a particular resource.*/ OC_REST_PRESENCE = (1 << 7), - #endif +#endif /** Allows OCDoResource caller to do discovery.*/ OC_REST_DISCOVER = (1 << 8) } OCMethod; @@ -655,8 +658,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. @@ -686,6 +693,7 @@ typedef enum OC_STACK_RESOURCE_CREATED, OC_STACK_RESOURCE_DELETED, OC_STACK_CONTINUE, + OC_STACK_RESOURCE_CHANGED, /** Success status code - END HERE.*/ /** Error status code - START HERE.*/ @@ -741,11 +749,11 @@ typedef enum OC_STACK_AUTHENTICATION_FAILURE, /** Insert all new error codes here!.*/ - #ifdef WITH_PRESENCE +#ifdef WITH_PRESENCE OC_STACK_PRESENCE_STOPPED = 128, OC_STACK_PRESENCE_TIMEOUT, OC_STACK_PRESENCE_DO_NOT_HANDLE, - #endif +#endif /** ERROR in stack.*/ OC_STACK_ERROR = 255 /** Error status code - END HERE.*/ @@ -833,11 +841,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; /** @@ -931,6 +949,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 @@ -1073,6 +1095,9 @@ typedef struct OCResourcePayload uint8_t bitmap; bool secure; uint16_t port; +#ifdef TCP_ADAPTER + uint16_t tcpPort; +#endif struct OCResourcePayload* next; } OCResourcePayload; @@ -1175,7 +1200,7 @@ typedef struct char *uri; /** Resource Type */ - char *type; + OCStringLL *type; /** Interface */ OCStringLL *interface; @@ -1216,7 +1241,7 @@ typedef struct char *sid; char* deviceName; char* specVersion; - char* dataModelVersion; + OCStringLL *dataModelVersions; OCStringLL *interfaces; OCStringLL *types; } OCDevicePayload; @@ -1226,7 +1251,7 @@ typedef struct OCPayload base; char* uri; OCPlatformInfo info; - char* rt; + OCStringLL* rt; OCStringLL* interfaces; } OCPlatformPayload; @@ -1281,6 +1306,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; @@ -1467,11 +1495,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 diff --git a/resource/csdk/stack/include/payload_logging.h b/resource/csdk/stack/include/payload_logging.h index b695d8971..14ca4b0dc 100644 --- a/resource/csdk/stack/include/payload_logging.h +++ b/resource/csdk/stack/include/payload_logging.h @@ -189,7 +189,10 @@ 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) @@ -232,8 +235,15 @@ static inline 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:"); @@ -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) { diff --git a/resource/csdk/stack/include/rdpayload.h b/resource/csdk/stack/include/rdpayload.h index 17c641719..1e65586a8 100644 --- a/resource/csdk/stack/include/rdpayload.h +++ b/resource/csdk/stack/include/rdpayload.h @@ -41,7 +41,7 @@ extern "C" { * @return ::CborNoError returns if successful and other Cbor error in case of error. * failed in creating CBOR. */ -CborError OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, size_t *size); +int64_t OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, size_t *size); /** * Converts CBOR to OCRDPayload. diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/SConscript b/resource/csdk/stack/samples/linux/SimpleClientServer/SConscript index fe696120d..6f8aaaa2a 100644 --- a/resource/csdk/stack/samples/linux/SimpleClientServer/SConscript +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/SConscript @@ -33,17 +33,22 @@ samples_env.PrependUnique(CPPPATH = [ '../../../../../connectivity/lib/libcoap-4.1.1' ]) -samples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) +compiler = env.get('CXX') +if 'g++' in compiler: + samples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) + samples_env.AppendUnique(LIBS=['pthread']) 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' ]) + samples_env.PrependUnique(LIBS = ['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']) 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']) diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/occlient.cpp b/resource/csdk/stack/samples/linux/SimpleClientServer/occlient.cpp index 23053e77a..573edc11a 100644 --- a/resource/csdk/stack/samples/linux/SimpleClientServer/occlient.cpp +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/occlient.cpp @@ -733,7 +733,7 @@ int InitPlatformDiscovery(OCQualityOfService qos) OCStackResult ret; OCCallbackData cbData; - char szQueryUri[64] = { 0 }; + char szQueryUri[MAX_QUERY_LENGTH] = { 0 }; snprintf(szQueryUri, sizeof (szQueryUri) - 1, PLATFORM_DISCOVERY_QUERY, discoveryAddr); @@ -758,7 +758,7 @@ int InitDeviceDiscovery(OCQualityOfService qos) OCStackResult ret; OCCallbackData cbData; - char szQueryUri[100] = { 0 }; + char szQueryUri[MAX_QUERY_LENGTH] = { 0 }; snprintf(szQueryUri, sizeof (szQueryUri) - 1, DEVICE_DISCOVERY_QUERY, discoveryAddr); @@ -781,7 +781,7 @@ int InitDiscovery(OCQualityOfService qos) { OCStackResult ret; OCCallbackData cbData; - char szQueryUri[100] = { 0 }; + char szQueryUri[MAX_QUERY_LENGTH] = { 0 }; snprintf(szQueryUri, sizeof (szQueryUri) - 1, RESOURCE_DISCOVERY_QUERY, discoveryAddr); diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/occlientcoll.cpp b/resource/csdk/stack/samples/linux/SimpleClientServer/occlientcoll.cpp index fee8870ce..f597bc27f 100644 --- a/resource/csdk/stack/samples/linux/SimpleClientServer/occlientcoll.cpp +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/occlientcoll.cpp @@ -350,7 +350,7 @@ int InitDiscovery() OCStackResult ret; OCCallbackData cbData; /* Start a discovery query*/ - char szQueryUri[64] = { 0 }; + char szQueryUri[MAX_QUERY_LENGTH] = { 0 }; strcpy(szQueryUri, RESOURCE_DISCOVERY_QUERY); diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp index cc5e968fb..9a0202008 100644 --- a/resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp @@ -27,6 +27,7 @@ #include <signal.h> #include <pthread.h> #include <array> +#include "oic_malloc.h" #include "ocstack.h" #include "logger.h" #include "ocpayload.h" @@ -74,6 +75,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 @@ -814,6 +817,8 @@ void DeletePlatformInfo() void DeleteDeviceInfo() { free (deviceInfo.deviceName); + free (deviceInfo.specVersion); + OCFreeOCStringLL (deviceInfo.dataModelVersions); } bool DuplicateString(char** targetString, const char* sourceString) @@ -917,12 +922,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 +1058,7 @@ int main(int argc, char* argv[]) exit (EXIT_FAILURE); } - registrationResult = SetDeviceInfo(deviceName); + registrationResult = SetDeviceInfo(deviceName, specVersion, dataModelVersions); if (registrationResult != OC_STACK_OK) { diff --git a/resource/csdk/stack/samples/linux/secure/SConscript b/resource/csdk/stack/samples/linux/secure/SConscript index e15ae78e7..fbb25a34b 100644 --- a/resource/csdk/stack/samples/linux/secure/SConscript +++ b/resource/csdk/stack/samples/linux/secure/SConscript @@ -38,7 +38,8 @@ if target_os not in ['windows', 'winrt']: # Note: 'pthread' is in libc for android. if target_os != 'android': - samples_env.AppendUnique(LIBS = ['-lpthread']) + samples_env.AppendUnique(LIBS = ['pthread']) + 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']) diff --git a/resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp b/resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp index 0f5d93b9f..caeed41ec 100644 --- a/resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp +++ b/resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp @@ -37,6 +37,7 @@ static int UnicastDiscovery = 0; static int TestCase = 0; static int ConnType = 0; +static int DevOwner = 0; static char DISCOVERY_QUERY[] = "%s/oic/res"; OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP; @@ -49,8 +50,10 @@ static OCConnectivityType ocConnType; //Secure Virtual Resource database for Iotivity Client application //It contains Client's Identity and the PSK credentials //of other devices which the client trusts -static char CRED_FILE[] = "oic_svr_db_client.dat"; - +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; @@ -89,6 +92,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 Non Device Owner"); + OIC_LOG(INFO, TAG, "-d 1 : Client as Device Owner"); } OCStackResult InvokeOCDoResource(std::ostringstream &query, @@ -299,18 +304,24 @@ int InitDiscovery() return ret; } -FILE* client_fopen(const char *path, const char *mode) +FILE* client_fopen_devowner(const char *path, const char *mode) { (void)path; - return fopen(CRED_FILE, mode); + return fopen(CRED_FILE_DEVOWNER, mode); } +FILE* client_fopen_nondevowner(const char *path, const char *mode) +{ + (void)path; + return fopen(CRED_FILE_NONDEVOWNER, mode); +} int main(int argc, char* argv[]) { int opt; struct timespec timeout; + OCPersistentStorage ps; - while ((opt = getopt(argc, argv, "u:t:c:")) != -1) + while ((opt = getopt(argc, argv, "u:t:c:d:")) != -1) { switch(opt) { @@ -323,6 +334,9 @@ int main(int argc, char* argv[]) case 'c': ConnType = atoi(optarg); break; + case 'd': + DevOwner = atoi(optarg); + break; default: PrintUsage(); return -1; @@ -350,7 +364,10 @@ int main(int argc, char* argv[]) // Initialize Persistent Storage for SVR database - OCPersistentStorage ps = { client_fopen, fread, fwrite, fclose, unlink }; + if (DevOwner) + ps = { client_fopen_devowner, fread, fwrite, fclose, unlink }; + else + ps = { client_fopen_nondevowner, fread, fwrite, fclose, unlink }; OCRegisterPersistentStorageHandler(&ps); /* Initialize OCStack*/ @@ -400,9 +417,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; } diff --git a/resource/csdk/stack/samples/linux/secure/occlientdirectpairing.cpp b/resource/csdk/stack/samples/linux/secure/occlientdirectpairing.cpp index 0979901f2..c47c881e9 100644 --- a/resource/csdk/stack/samples/linux/secure/occlientdirectpairing.cpp +++ b/resource/csdk/stack/samples/linux/secure/occlientdirectpairing.cpp @@ -270,10 +270,11 @@ OCStackApplicationResult discoveryReqCB(void*, OCDoHandle, }
// This is a function called back when direct-pairing status is changed
-void pairingReqCB(OCDPDev_t* peer, OCStackResult result)
+void pairingReqCB(void *ctx, OCDPDev_t* peer, OCStackResult result)
{
OIC_LOG(INFO, TAG, "Callback Context for Direct-Pairing establishment\n");
+ (void) ctx;
if (OC_STACK_OK == result)
{
OIC_LOG_V(INFO, TAG,
@@ -359,7 +360,7 @@ OCStackResult DoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber) // start direct pairing
OIC_LOG(INFO, TAG, " Start Direct Pairing..");
- if(OC_STACK_OK != OCDoDirectPairing(peer, pmSel, pinNumber, pairingReqCB))
+ if(OC_STACK_OK != OCDoDirectPairing(NULL, peer, pmSel, pinNumber, pairingReqCB))
{
OIC_LOG(ERROR, TAG, "OCDoDirectPairing API error");
return OC_STACK_ERROR;
diff --git a/resource/csdk/stack/samples/linux/secure/oic_amss_db.dat b/resource/csdk/stack/samples/linux/secure/oic_amss_db.dat Binary files differindex ff0932f48..6891ae5b0 100644 --- a/resource/csdk/stack/samples/linux/secure/oic_amss_db.dat +++ b/resource/csdk/stack/samples/linux/secure/oic_amss_db.dat diff --git a/resource/csdk/stack/samples/linux/secure/oic_amss_db.json b/resource/csdk/stack/samples/linux/secure/oic_amss_db.json index 4d958e957..97a952a78 100644 --- a/resource/csdk/stack/samples/linux/secure/oic_amss_db.json +++ b/resource/csdk/stack/samples/linux/secure/oic_amss_db.json @@ -8,44 +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": ""
- },
- {
- "href": "/oic/res/types/d",
- "rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
},
{
"href": "/oic/ad",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.ad"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/acl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.acl"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/amacl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.amacl"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 2
@@ -56,14 +50,14 @@ {
"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": 2
@@ -89,7 +83,7 @@ "deviceuuid": "31393139-3139-3139-3139-313931393139",
"devowneruuid": "61646D69-6E44-6576-6963-655555494430",
"rowneruuid": "31393139-3139-3139-3139-313931393139",
- "dpc": false
+ "x.org.iotivity.dpc": false
},
"cred": {
"creds": [
diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client.dat b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client.dat Binary files differindex 7dbbb0a91..3d258b7fa 100644 --- a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client.dat +++ b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client.dat diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client.json b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client.json index 4b19514fd..d0595e75f 100644 --- a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client.json +++ b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client.json @@ -1,108 +1,102 @@ -{
- "acl": {
- "aclist": {
- "aces": [
- {
- "subjectuuid": "*",
- "resources": [
- {
- "href": "/oic/res",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/d",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "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": ""
- },
- {
- "href": "/oic/sec/amacl",
- "rel": "",
- "rt": "",
- "if": ""
- }
- ],
- "permission": 2
- },
- {
- "subjectuuid": "*",
- "resources": [
- {
- "href": "/oic/sec/doxm",
- "rel": "",
- "rt": "",
- "if": ""
- } ,
- {
- "href": "/oic/sec/pstat",
- "rel": "",
- "rt": "",
- "if": ""
- }
- ],
- "permission": 2
- }
- ]
- },
- "rowneruuid" : "32323232-3232-3232-3232-323232323232"
- },
- "pstat": {
- "isop": true,
- "deviceuuid": "32323232-3232-3232-3232-323232323232",
- "rowneruuid": "32323232-3232-3232-3232-323232323232",
- "cm": 0,
- "tm": 0,
- "om": 3,
- "sm": 3
- },
- "doxm": {
- "oxms": [0],
- "oxmsel": 0,
- "sct": 1,
- "owned": true,
- "deviceuuid": "32323232-3232-3232-3232-323232323232",
- "devowneruuid": "32323232-3232-3232-3232-323232323232",
- "rowneruuid": "32323232-3232-3232-3232-323232323232",
- "dpc": false
- },
- "cred": {
- "creds": [
- {
- "credid": 1,
- "subjectuuid": "31313131-3131-3131-3131-313131313131",
- "credtype": 1,
- "privatedata": {
- "data": "AAAAAAAAAAAAAAAA",
- "encoding": "oic.sec.encoding.raw"
- }
- }
- ],
- "rowneruuid": "32323232-3232-3232-3232-323232323232"
- }
-}
+{ + "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"] + }, + { + "href": "/oic/ad", + "rel": "", + "rt": ["oic.wk.ad"], + "if": ["oic.if.baseline"] + }, + { + "href": "/oic/sec/acl", + "rel": "", + "rt": ["oic.r.acl"], + "if": ["oic.if.baseline"] + }, + { + "href": "/oic/sec/amacl", + "rel": "", + "rt": ["oic.r.amacl"], + "if": ["oic.if.baseline"] + } + ], + "permission": 2 + }, + { + "subjectuuid": "*", + "resources": [ + { + "href": "/oic/sec/doxm", + "rel": "", + "rt": ["oic.r.doxm"], + "if": ["oic.if.baseline"] + }, + { + "href": "/oic/sec/pstat", + "rel": "", + "rt": ["oic.r.pstat"], + "if": ["oic.if.baseline"] + } + ], + "permission": 2 + } + ] + }, + "rowneruuid" : "32323232-3232-3232-3232-323232323232" + }, + "pstat": { + "isop": true, + "deviceuuid": "32323232-3232-3232-3232-323232323232", + "rowneruuid": "32323232-3232-3232-3232-323232323232", + "cm": 0, + "tm": 0, + "om": 3, + "sm": 3 + }, + "doxm": { + "oxms": [0], + "oxmsel": 0, + "sct": 1, + "owned": true, + "deviceuuid": "32323232-3232-3232-3232-323232323232", + "devowneruuid": "32323232-3232-3232-3232-323232323232", + "rowneruuid": "32323232-3232-3232-3232-323232323232", + "x.org.iotivity.dpc": false + }, + "cred": { + "creds": [ + { + "credid": 1, + "subjectuuid": "31313131-3131-3131-3131-313131313131", + "credtype": 1, + "privatedata": { + "data": "AAAAAAAAAAAAAAAA", + "encoding": "oic.sec.encoding.raw" + } + } + ], + "rowneruuid": "32323232-3232-3232-3232-323232323232" + } +} diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_devowner.dat b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_devowner.dat Binary files differnew file mode 100644 index 000000000..3d258b7fa --- /dev/null +++ b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_devowner.dat diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_devowner.json b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_devowner.json new file mode 100644 index 000000000..4837af9c6 --- /dev/null +++ b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_devowner.json @@ -0,0 +1,102 @@ +{
+ "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"]
+ },
+ {
+ "href": "/oic/ad",
+ "rel": "",
+ "rt": ["oic.wk.ad"],
+ "if": ["oic.if.baseline"]
+ },
+ {
+ "href": "/oic/sec/acl",
+ "rel": "",
+ "rt": ["oic.r.acl"],
+ "if": ["oic.if.baseline"]
+ },
+ {
+ "href": "/oic/sec/amacl",
+ "rel": "",
+ "rt": ["oic.r.amacl"],
+ "if": ["oic.if.baseline"]
+ }
+ ],
+ "permission": 2
+ },
+ {
+ "subjectuuid": "*",
+ "resources": [
+ {
+ "href": "/oic/sec/doxm",
+ "rel": "",
+ "rt": ["oic.r.doxm"],
+ "if": ["oic.if.baseline"]
+ },
+ {
+ "href": "/oic/sec/pstat",
+ "rel": "",
+ "rt": ["oic.r.pstat"],
+ "if": ["oic.if.baseline"]
+ }
+ ],
+ "permission": 2
+ }
+ ]
+ },
+ "rowneruuid" : "32323232-3232-3232-3232-323232323232"
+ },
+ "pstat": {
+ "isop": true,
+ "deviceuuid": "32323232-3232-3232-3232-323232323232",
+ "rowneruuid": "32323232-3232-3232-3232-323232323232",
+ "cm": 0,
+ "tm": 0,
+ "om": 3,
+ "sm": 3
+ },
+ "doxm": {
+ "oxms": [0],
+ "oxmsel": 0,
+ "sct": 1,
+ "owned": true,
+ "deviceuuid": "32323232-3232-3232-3232-323232323232",
+ "devowneruuid": "32323232-3232-3232-3232-323232323232",
+ "rowneruuid": "32323232-3232-3232-3232-323232323232",
+ "x.org.iotivity.dpc": false
+ },
+ "cred": {
+ "creds": [
+ {
+ "credid": 1,
+ "subjectuuid": "31313131-3131-3131-3131-313131313131",
+ "credtype": 1,
+ "privatedata": {
+ "data": "AAAAAAAAAAAAAAAA",
+ "encoding": "oic.sec.encoding.raw"
+ }
+ }
+ ],
+ "rowneruuid": "32323232-3232-3232-3232-323232323232"
+ }
+}
diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat Binary files differindex 43b7a1c5c..e070ea4c5 100644 --- a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat +++ b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.json b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.json index 588ac54d0..4fcd6db26 100644 --- a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.json +++ b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.json @@ -1,100 +1,82 @@ -{
- "acl": {
- "aclist": {
- "aces": [
- {
- "subjectuuid": "*",
- "resources": [
- {
- "href": "/oic/res",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/d",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "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": ""
- }
- ],
- "permission": 2
- },
- {
- "subjectuuid": "*",
- "resources": [
- {
- "href": "/oic/sec/doxm",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/sec/pstat",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/sec/acl",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/sec/cred",
- "rel": "",
- "rt": "",
- "if": ""
- }
- ],
- "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",
- "dpc": false
- }
-}
+{ + "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.org.iotivity.dpc": false + } +} diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_nondevowner.dat b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_nondevowner.dat Binary files differnew file mode 100644 index 000000000..b726fd61f --- /dev/null +++ b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_nondevowner.dat diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_nondevowner.json b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_nondevowner.json new file mode 100644 index 000000000..5746fc0c3 --- /dev/null +++ b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_nondevowner.json @@ -0,0 +1,102 @@ +{
+ "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"]
+ },
+ {
+ "href": "/oic/ad",
+ "rel": "",
+ "rt": ["oic.wk.ad"],
+ "if": ["oic.if.baseline"]
+ },
+ {
+ "href": "/oic/sec/acl",
+ "rel": "",
+ "rt": ["oic.r.acl"],
+ "if": ["oic.if.baseline"]
+ },
+ {
+ "href": "/oic/sec/amacl",
+ "rel": "",
+ "rt": ["oic.r.amacl"],
+ "if": ["oic.if.baseline"]
+ }
+ ],
+ "permission": 2
+ },
+ {
+ "subjectuuid": "*",
+ "resources": [
+ {
+ "href": "/oic/sec/doxm",
+ "rel": "",
+ "rt": ["oic.r.doxm"],
+ "if": ["oic.if.baseline"]
+ },
+ {
+ "href": "/oic/sec/pstat",
+ "rel": "",
+ "rt": ["oic.r.pstat"],
+ "if": ["oic.if.baseline"]
+ }
+ ],
+ "permission": 2
+ }
+ ]
+ },
+ "rowneruuid" : "31393139-3139-3139-3139-313931393139"
+ },
+ "pstat": {
+ "isop": true,
+ "deviceuuid": "31393139-3139-3139-3139-313931393139",
+ "rowneruuid": "31393139-3139-3139-3139-313931393139",
+ "cm": 0,
+ "tm": 0,
+ "om": 3,
+ "sm": 3
+ },
+ "doxm": {
+ "oxms": [0],
+ "oxmsel": 0,
+ "sct": 1,
+ "owned": true,
+ "deviceuuid": "31393139-3139-3139-3139-313931393139",
+ "devowneruuid": "31393139-3139-3139-3139-313931393139",
+ "rowneruuid": "31393139-3139-3139-3139-313931393139",
+ "x.org.iotivity.dpc": false
+ },
+ "cred": {
+ "creds": [
+ {
+ "credid": 1,
+ "subjectuuid": "31313131-3131-3131-3131-313131313131",
+ "credtype": 1,
+ "privatedata": {
+ "data": "BBBBBBBBBBBBBBBB",
+ "encoding": "oic.sec.encoding.raw"
+ }
+ }
+ ],
+ "rowneruuid": "31393139-3139-3139-3139-313931393139"
+ }
+}
diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat Binary files differindex 693c81db5..824fe7b2b 100644 --- a/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat +++ b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.json b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.json index 920c94521..a5ebfcbbc 100644 --- a/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.json +++ b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.json @@ -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": ""
- },
- {
- "href": "/oic/res/d",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/res/types/d",
- "rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
},
{
"href": "/oic/ad",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.ad"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/acl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.acl"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/amacl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.amacl"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 2
@@ -62,14 +50,14 @@ {
"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": 2
@@ -80,31 +68,29 @@ {
"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": 8
},
{
- "subjectuuid": "31313131-3232-3232-3333-333334343434",
+ "subjectuuid": "31393139-3139-3139-3139-313931393139",
"resources": [
{
"href": "/a/led",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
}
],
- "permission": 6,
- "period" : ["20150630T060000/20150630T220000", "20150630T060000/20150630T200000"],
- "recurrence" : ["FREQ=DAILY; BYDAY=MO, WE, FR", "FREQ=DAILY; BYDAY=TU, TH; UNTIL=20160630"]
+ "permission": 6
},
{
"subjectuuid": "37373737-3737-3737-3737-373737373737",
@@ -112,13 +98,11 @@ {
"href": "/a/led",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
}
],
- "permission": 6,
- "period" : ["20150630T060000/20150630T220000"],
- "recurrence" : ["FREQ=DAILY; UNTIL=20150630"]
+ "permission": 6
}
]
},
@@ -141,7 +125,7 @@ "deviceuuid": "31313131-3131-3131-3131-313131313131",
"devowneruuid": "32323232-3232-3232-3232-323232323232",
"rowneruuid": "31313131-3131-3131-3131-313131313131",
- "dpc": false
+ "x.org.iotivity.dpc": false
},
"cred": {
"creds": [
diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat Binary files differindex 605683ab4..97eae6dea 100644 --- a/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat +++ b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.json b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.json new file mode 100644 index 000000000..25145b9bd --- /dev/null +++ b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.json @@ -0,0 +1,112 @@ +{
+ "acl": {
+ "aclist": {
+ "aces": [
+ {
+ "subjectuuid": "*",
+ "resources": [
+ {
+ "href": "/oic/res",
+ "rt": ["oic.wk.res"],
+ "if": ["oic.if.ll"],
+ "rel": ""
+ },
+ {
+ "href": "/oic/d",
+ "rt": ["oic.wk.d"],
+ "if": ["oic.if.baseline", "oic.if.r"],
+ "rel": ""
+ },
+ {
+ "href": "/oic/p",
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"],
+ "rel": ""
+ }
+ ],
+ "permission": 2
+ },
+ {
+ "subjectuuid": "*",
+ "resources": [
+ {
+ "href": "/oic/sec/doxm",
+ "rt": ["oic.r.doxm"],
+ "if": ["oic.if.baseline"],
+ "rel": ""
+ },
+ {
+ "href": "/oic/sec/pstat",
+ "rt": ["oic.r.pstat"],
+ "if": ["oic.if.baseline"],
+ "rel": ""
+ },
+ {
+ "href": "/oic/sec/acl",
+ "rt": ["oic.r.acl"],
+ "if": ["oic.if.baseline"],
+ "rel": ""
+ },
+ {
+ "href": "/oic/sec/cred",
+ "rt": ["oic.r.cred"],
+ "if": ["oic.if.baseline"],
+ "rel": ""
+ }
+ ],
+ "permission": 6
+ },
+ {
+
"subjectuuid": "*",
+ "resources": [
+ {
+ "href": "/oic/sec/pconf",
+ "rt": ["oic.r.pconf"],
+ "if": ["oic.if.baseline"],
+ "rel": ""
+ },
+ {
+ "href": "/oic/sec/dpairing",
+ "rt": ["oic.r.dpairing"],
+ "if": ["oic.if.baseline"],
+
"rel": ""
+ }
+ ],
+ "permission": 6
+ },
+ {
+ "subjectuuid": "*",
+ "resources": [
+ {
+ "href": "/oic/sec/ver",
+ "rt": ["oic.r.ver"],
+ "if": ["oic.if.baseline"],
+ "rel": ""
+ }
+ ],
+ "permission":2
+ }
+ ]
+ },
+ "rowneruuid": "6a757374-776f-726b-4465-765575696430"
+ },
+ "pstat": {
+ "isop": false,
+ "deviceuuid": "6a757374-776f-726b-4465-765575696430",
+ "cm": 2,
+ "tm": 0,
+ "om": 3,
+ "sm": 3,
+ "rowneruuid": "6a757374-776f-726b-4465-765575696430"
+ },
+ "doxm": {
+ "oxms": [0],
+ "oxmsel": 0,
+ "sct": 1,
+ "owned": false,
+ "deviceuuid": "6a757374-776f-726b-4465-765575696430",
+ "devowneruuid": "",
+ "rowneruuid": "6a757374-776f-726b-4465-765575696430",
+ "x.org.iotivity.dpc": false
+ }
+}
\ No newline at end of file diff --git a/resource/csdk/stack/samples/tizen/SimpleClientServer/occlient.cpp b/resource/csdk/stack/samples/tizen/SimpleClientServer/occlient.cpp index a128a73a6..8b3d86ebc 100644 --- a/resource/csdk/stack/samples/tizen/SimpleClientServer/occlient.cpp +++ b/resource/csdk/stack/samples/tizen/SimpleClientServer/occlient.cpp @@ -20,6 +20,7 @@ //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #include <stdio.h> +#include <glib.h> #include <stdlib.h> #include <string.h> #include <signal.h> @@ -51,6 +52,9 @@ static int g_unicastDiscovery = 0; static int g_testCase = 0; static int g_connectivity = 0; +static GMainLoop *g_mainloop = NULL; +pthread_t g_thread; + static const char *DEVICE_DISCOVERY_QUERY = "%s/oic/d"; static const char *PLATFORM_DISCOVERY_QUERY = "%s/oic/p"; static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res"; @@ -715,7 +719,7 @@ int InitPlatformDiscovery(OCQualityOfService qos) OCStackResult ret; OCCallbackData cbData; - char szQueryUri[64] = { 0 }; + char szQueryUri[MAX_QUERY_LENGTH] = { 0 }; snprintf(szQueryUri, sizeof (szQueryUri) - 1, PLATFORM_DISCOVERY_QUERY, g_discoveryAddr); @@ -740,7 +744,7 @@ int InitDeviceDiscovery(OCQualityOfService qos) OCStackResult ret; OCCallbackData cbData; - char szQueryUri[100] = { 0 }; + char szQueryUri[MAX_QUERY_LENGTH] = { 0 }; snprintf(szQueryUri, sizeof (szQueryUri) - 1, DEVICE_DISCOVERY_QUERY, g_discoveryAddr); @@ -763,7 +767,7 @@ int InitDiscovery(OCQualityOfService qos) { OCStackResult ret; OCCallbackData cbData; - char szQueryUri[100] = { 0 }; + char szQueryUri[MAX_QUERY_LENGTH] = { 0 }; snprintf(szQueryUri, sizeof (szQueryUri) - 1, RESOURCE_DISCOVERY_QUERY, g_discoveryAddr); @@ -781,10 +785,52 @@ int InitDiscovery(OCQualityOfService qos) return ret; } +void *GMainLoopThread(void *param) +{ + + if (g_unicastDiscovery == 0 && g_testCase == TEST_DISCOVER_DEV_REQ) + { + InitDeviceDiscovery(OC_LOW_QOS); + } + else if (g_unicastDiscovery == 0 && g_testCase == TEST_DISCOVER_PLATFORM_REQ) + { + InitPlatformDiscovery(OC_LOW_QOS); + } + else + { + InitDiscovery(OC_LOW_QOS); + } + + while (!gQuitFlag) + { + if (OCProcess() != OC_STACK_OK) + { + cout << "\nOCStack process error"; + return NULL; + } +#ifndef ROUTING_GATEWAY + sleep(1); +#endif + } + + if (g_mainloop) + { + g_main_loop_quit(g_mainloop); + } + return NULL; +} + int main(int argc, char* argv[]) { int opt; + g_mainloop = g_main_loop_new(NULL, FALSE); + if(!g_mainloop) + { + printf("g_main_loop_new failed\n"); + return 0; + } + while ((opt = getopt(argc, argv, "u:t:c:")) != -1) { switch(opt) @@ -872,35 +918,20 @@ int main(int argc, char* argv[]) } } - if (g_unicastDiscovery == 0 && g_testCase == TEST_DISCOVER_DEV_REQ) - { - InitDeviceDiscovery(OC_LOW_QOS); - } - else if (g_unicastDiscovery == 0 && g_testCase == TEST_DISCOVER_PLATFORM_REQ) - { - InitPlatformDiscovery(OC_LOW_QOS); - } - else - { - InitDiscovery(OC_LOW_QOS); - } // Break from loop with Ctrl+C OIC_LOG(INFO, TAG, "Entering occlient main loop..."); signal(SIGINT, handleSigInt); - while (!gQuitFlag) - { - if (OCProcess() != OC_STACK_OK) - { - cout << "\nOCStack process error\n"; - return 0; - } -#ifndef ROUTING_GATEWAY - sleep(1); -#endif + int result = pthread_create(&g_thread, NULL, GMainLoopThread, (void *)NULL); + if (result < 0) + { + printf("pthread_create failed in initialize\n"); + return 0; } + g_main_loop_run(g_mainloop); + cout << "\nExiting occlient main loop...\n"; if (OCStop() != OC_STACK_OK) diff --git a/resource/csdk/stack/samples/tizen/SimpleClientServer/ocrouting.cpp b/resource/csdk/stack/samples/tizen/SimpleClientServer/ocrouting.cpp index 7039f930a..bbe304c8f 100644 --- a/resource/csdk/stack/samples/tizen/SimpleClientServer/ocrouting.cpp +++ b/resource/csdk/stack/samples/tizen/SimpleClientServer/ocrouting.cpp @@ -18,7 +18,7 @@ * ******************************************************************/ - +#include <glib.h> #include <stdio.h> #include <string.h> #include <string> @@ -37,6 +37,8 @@ using namespace std; #define TAG "ocrouting" int gQuitFlag = 0; +static GMainLoop *g_mainloop = NULL; +pthread_t g_thread; /* SIGINT handler: set gQuitFlag to 1 for graceful termination */ void handleSigInt(int signum) @@ -47,9 +49,37 @@ void handleSigInt(int signum) } } +void *GMainLoopThread(void *param) +{ + + while (!gQuitFlag) + { + if (OCProcess() != OC_STACK_OK) + { + cout << "\nOCStack process error"; + return NULL; + } +#ifndef ROUTING_GATEWAY + sleep(1); +#endif + } + + if (g_mainloop) + { + g_main_loop_quit(g_mainloop); + } + return NULL; +} + int main() { cout << "\nOCRouting sample is starting..."; + g_mainloop = g_main_loop_new(NULL, FALSE); + if(!g_mainloop) + { + printf("g_main_loop_new failed\n"); + return 0; + } if (OCInit(NULL, 0, OC_GATEWAY) != OC_STACK_OK) { @@ -62,15 +92,16 @@ int main() signal(SIGINT, handleSigInt); - while (!gQuitFlag) + + int result = pthread_create(&g_thread, NULL, GMainLoopThread, (void *)NULL); + if (result < 0) { - if (OCProcess() != OC_STACK_OK) - { - cout << "\nOCStack process error"; - return 0; - } + printf("pthread_create failed in initialize\n"); + return 0; } + g_main_loop_run(g_mainloop); + cout << "\nExiting ocrouting main loop..."; if (OCStop() != OC_STACK_OK) diff --git a/resource/csdk/stack/samples/tizen/SimpleClientServer/ocserver.cpp b/resource/csdk/stack/samples/tizen/SimpleClientServer/ocserver.cpp index faf5108d3..b5fc0ca59 100644 --- a/resource/csdk/stack/samples/tizen/SimpleClientServer/ocserver.cpp +++ b/resource/csdk/stack/samples/tizen/SimpleClientServer/ocserver.cpp @@ -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" @@ -44,6 +45,9 @@ static int gObserveNotifyType = 3; int gQuitFlag = 0; int gLightUnderObservation = 0; +static GMainLoop *g_mainloop = NULL; +pthread_t g_thread; + static LightResource Light; // This variable determines instance number of the Light resource. // Used by POST method to create a new instance of Light resource. @@ -73,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 @@ -804,6 +810,8 @@ void DeletePlatformInfo() void DeleteDeviceInfo() { free (deviceInfo.deviceName); + free (deviceInfo.specVersion); + OCFreeOCStringLL (deviceInfo.dataModelVersions); } bool DuplicateString(char** targetString, const char* sourceString) @@ -907,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; } @@ -923,12 +941,41 @@ static void PrintUsage() cout << "\n-o 1 : Notify list of observers"; } +void *GMainLoopThread(void *param) +{ + + while (!gQuitFlag) + { + if (OCProcess() != OC_STACK_OK) + { + cout << "\nOCStack process error"; + return NULL; + } +#ifndef ROUTING_GATEWAY + sleep(1); +#endif + } + + if (g_mainloop) + { + g_main_loop_quit(g_mainloop); + } + return NULL; +} + int main(int argc, char* argv[]) { pthread_t threadId; pthread_t threadId_presence; int opt; + g_mainloop = g_main_loop_new(NULL, FALSE); + if(!g_mainloop) + { + printf("g_main_loop_new failed\n"); + return 0; + } + while ((opt = getopt(argc, argv, "o:")) != -1) { switch(opt) @@ -955,6 +1002,7 @@ int main(int argc, char* argv[]) cout << "\nOCStack init error"; return 0; } + #ifdef WITH_PRESENCE if (OCStartPresence(0) != OC_STACK_OK) { @@ -984,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) { @@ -1035,18 +1083,15 @@ int main(int argc, char* argv[]) signal(SIGINT, handleSigInt); - while (!gQuitFlag) + int result = pthread_create(&g_thread, NULL, GMainLoopThread, (void *)NULL); + if (result < 0) { - if (OCProcess() != OC_STACK_OK) - { - cout << "\nOCStack process error"; - return 0; - } -#ifndef ROUTING_GATEWAY - sleep(1); -#endif + printf("pthread_create failed in initialize\n"); + return 0; } + g_main_loop_run(g_mainloop); + /* * Cancel the Light thread and wait for it to terminate */ diff --git a/resource/csdk/stack/samples/tizen/SimpleClientServer/packaging/com.oic.ri.sample.spec b/resource/csdk/stack/samples/tizen/SimpleClientServer/packaging/com.oic.ri.sample.spec index f719742ec..9aabba502 100644 --- a/resource/csdk/stack/samples/tizen/SimpleClientServer/packaging/com.oic.ri.sample.spec +++ b/resource/csdk/stack/samples/tizen/SimpleClientServer/packaging/com.oic.ri.sample.spec @@ -1,9 +1,10 @@ %define PREFIX /usr/apps/com.oic.ri.sample %define ROOTDIR %{_builddir}/%{name}-%{version} +%{!?VERBOSE: %define VERBOSE 1} 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 @@ -30,7 +31,7 @@ OIC RIsample application %build scons TARGET_OS=tizen -c -scons TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} ROUTING=%{ROUTING} +scons VERBOSE=%{VERBOSE} TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} ROUTING=%{ROUTING} %install diff --git a/resource/csdk/stack/samples/tizen/build/packaging/com.oic.ri.spec b/resource/csdk/stack/samples/tizen/build/packaging/com.oic.ri.spec index 7e559c1b5..9f57c683b 100644 --- a/resource/csdk/stack/samples/tizen/build/packaging/com.oic.ri.spec +++ b/resource/csdk/stack/samples/tizen/build/packaging/com.oic.ri.spec @@ -2,10 +2,11 @@ %define ROOTDIR %{_builddir}/%{name}-%{version} %define DEST_INC_DIR %{buildroot}/%{_includedir}/OICHeaders %define DEST_LIB_DIR %{buildroot}/%{_libdir} +%{!?VERBOSE: %define VERBOSE 1} 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 @@ -36,7 +37,7 @@ SLP oicri application echo %{ROOTDIR} scons TARGET_OS=tizen -c -scons TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} LOGGING=%{LOGGING} ROUTING=%{ROUTING} +scons VERBOSE=%{VERBOSE} TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} LOGGING=%{LOGGING} ROUTING=%{ROUTING} %install mkdir -p %{DEST_INC_DIR} @@ -66,6 +67,7 @@ cp resource/oc_logger/include/targets/oc_ostream_logger.h %{DEST_INC_DIR} cp resource/csdk/stack/include/ocpresence.h %{DEST_INC_DIR} cp resource/csdk/stack/include/ocpayload.h %{DEST_INC_DIR} cp resource/c_common/platform_features.h %{DEST_INC_DIR} +cp resource/c_common/*/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} diff --git a/resource/csdk/stack/src/occlientcb.c b/resource/csdk/stack/src/occlientcb.c index 9b3c19dd5..a24efed93 100644 --- a/resource/csdk/stack/src/occlientcb.c +++ b/resource/csdk/stack/src/occlientcb.c @@ -214,11 +214,11 @@ static void CheckAndDeleteTimedOutCB(ClientCB* cbNode) } ClientCB* GetClientCB(const CAToken_t token, uint8_t tokenLength, - OCDoHandle handle, const char * requestUri) + OCDoHandle handle, const char * requestUri) { ClientCB* out = NULL; - if (token && *token && tokenLength <= CA_MAX_TOKEN_LEN && tokenLength > 0) + if (token && tokenLength <= CA_MAX_TOKEN_LEN && tokenLength > 0) { OIC_LOG (INFO, TAG, "Looking for token"); OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength); diff --git a/resource/csdk/stack/src/ocobserve.c b/resource/csdk/stack/src/ocobserve.c index 636572adb..2051f7388 100644 --- a/resource/csdk/stack/src/ocobserve.c +++ b/resource/csdk/stack/src/ocobserve.c @@ -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; } diff --git a/resource/csdk/stack/src/ocpayload.c b/resource/csdk/stack/src/ocpayload.c index 3c302a3b9..5e0fb71f5 100644 --- a/resource/csdk/stack/src/ocpayload.c +++ b/resource/csdk/stack/src/ocpayload.c @@ -18,7 +18,10 @@ // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// 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); @@ -473,7 +477,7 @@ bool OCRepPayloadIsNull(const OCRepPayload* payload, const char* name) if (!val) { - return false; + return true; } return val->type == OCREP_PROP_NULL; @@ -971,7 +975,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 +1277,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,7 +1478,8 @@ OCResourcePayload* OCDiscoveryPayloadGetResource(OCDiscoveryPayload* payload, si return NULL; } -static OCResourcePayload* OCCopyResource(const OCResource* res, uint16_t port) +static OCResourcePayload* OCCopyResource(const OCResource* res, uint16_t securePort, + uint16_t tcpPort) { OCResourcePayload* pl = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload)); if (!pl) @@ -1481,15 +1574,17 @@ static OCResourcePayload* OCCopyResource(const OCResource* res, uint16_t port) pl->bitmap = res->resourceProperties & (OC_OBSERVABLE | OC_DISCOVERABLE); pl->secure = (res->resourceProperties & OC_SECURE) != 0; - pl->port = port; - + pl->port = securePort; +#ifdef TCP_ADAPTER + pl->tcpPort = tcpPort; +#endif return pl; } void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res, - uint16_t port) + uint16_t securePort, uint16_t tcpPort) { - OCDiscoveryPayloadAddNewResource(payload, OCCopyResource(res, port)); + OCDiscoveryPayloadAddNewResource(payload, OCCopyResource(res, securePort, tcpPort)); } bool OCResourcePayloadAddStringLL(OCStringLL **stringLL, const char *value) @@ -1567,7 +1662,7 @@ 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); OCDiscoveryResourceDestroy(payload->resources); @@ -1604,8 +1699,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; } @@ -1636,7 +1731,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); @@ -1691,7 +1786,7 @@ OCPlatformPayload* OCPlatformPayloadCreate(const OCPlatformInfo* platformInfo) OCResourcePayloadAddStringLL(&payload->interfaces, OC_RSRVD_INTERFACE_DEFAULT); OCResourcePayloadAddStringLL(&payload->interfaces, OC_RSRVD_INTERFACE_READ); - payload->rt = OICStrdup(OC_RSRVD_RESOURCE_TYPE_PLATFORM); + OCResourcePayloadAddStringLL(&payload->rt, OC_RSRVD_RESOURCE_TYPE_PLATFORM); OCCopyPlatformInfo(platformInfo, payload); return payload; @@ -1720,7 +1815,7 @@ void OCPlatformPayloadDestroy(OCPlatformPayload* payload) } OICFree(payload->uri); OCPlatformInfoDestroy(&payload->info); - OICFree(payload->rt); + OCFreeOCStringLL(payload->rt); OCFreeOCStringLL(payload->interfaces); OICFree(payload); } diff --git a/resource/csdk/stack/src/ocpayloadconvert.c b/resource/csdk/stack/src/ocpayloadconvert.c index 9f1bde649..033e8372c 100644 --- a/resource/csdk/stack/src/ocpayloadconvert.c +++ b/resource/csdk/stack/src/ocpayloadconvert.c @@ -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, @@ -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,19 +266,13 @@ 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 @@ -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); @@ -358,6 +353,14 @@ static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload *payload, uint8_t *o VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding secure port value"); } +#ifdef TCP_ADAPTER + err |= cbor_encode_text_string(&policyMap, OC_RSRVD_TCP_PORT, + sizeof(OC_RSRVD_TCP_PORT) - 1); + VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding tcp port tag"); + err |= cbor_encode_uint(&policyMap, resource->tcpPort); + VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding tcp port value"); +#endif + err |= cbor_encoder_close_container(&linkMap, &policyMap); VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing policy map"); @@ -389,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; @@ -424,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"); @@ -506,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."); } diff --git a/resource/csdk/stack/src/ocpayloadparse.c b/resource/csdk/stack/src/ocpayloadparse.c index 4763299c6..c0cc4c206 100644 --- a/resource/csdk/stack/src/ocpayloadparse.c +++ b/resource/csdk/stack/src/ocpayloadparse.c @@ -248,7 +248,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"); } @@ -340,6 +340,16 @@ static OCStackResult OCParseDiscoveryPayload(OCPayload **outPayload, CborValue * VERIFY_CBOR_SUCCESS(TAG, err, "to find port value"); } +#ifdef TCP_ADAPTER + // TCP Port + err = cbor_value_map_find_value(&policyMap, OC_RSRVD_TCP_PORT, &curVal); + if (cbor_value_is_valid(&curVal)) + { + err = cbor_value_get_int(&curVal, (int *)&resource->tcpPort); + VERIFY_CBOR_SUCCESS(TAG, err, "to find tcp port value"); + } +#endif + err = cbor_value_advance(&resourceMap); VERIFY_CBOR_SUCCESS(TAG, err, "to advance resource map"); @@ -431,13 +441,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"); @@ -456,7 +470,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; @@ -562,7 +576,7 @@ static OCStackResult OCParsePlatformPayload(OCPayload **outPayload, CborValue *r VERIFY_CBOR_SUCCESS(TAG, err, "to find resource type tag"); 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"); } @@ -1169,17 +1183,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 diff --git a/resource/csdk/stack/src/ocresource.c b/resource/csdk/stack/src/ocresource.c index d109ba3a8..0e59dafd9 100755 --- a/resource/csdk/stack/src/ocresource.c +++ b/resource/csdk/stack/src/ocresource.c @@ -111,6 +111,29 @@ static OCStackResult GetSecurePortInfo(OCDevAddr *endpoint, uint16_t *port) return OC_STACK_OK; } +#ifdef TCP_ADAPTER +/* This method will retrieve the tcp port */ +static OCStackResult GetTCPPortInfo(OCDevAddr *endpoint, uint16_t *port) +{ + uint16_t p = 0; + + if (endpoint->adapter == OC_ADAPTER_IP) + { + if (endpoint->flags & OC_IP_USE_V4) + { + p = caglobals.tcp.ipv4.port; + } + else if (endpoint->flags & OC_IP_USE_V6) + { + p = caglobals.tcp.ipv6.port; + } + } + + *port = p; + return OC_STACK_OK; +} +#endif + /* * Function will extract 0, 1 or 2 filters from query. * More than 2 filters or unsupported filters will result in error. @@ -131,6 +154,12 @@ static OCStackResult ExtractFiltersFromQuery(char *query, char **filterOne, char OIC_LOG_V(INFO, TAG, "Extracting params from %s", query); + if (strnlen(query, MAX_QUERY_LENGTH) >= MAX_QUERY_LENGTH) + { + OIC_LOG(ERROR, TAG, "Query exceeds maximum length."); + return OC_STACK_INVALID_QUERY; + } + char *keyValuePair = strtok_r (query, OC_QUERY_SEPARATOR, &restOfQuery); while(keyValuePair) @@ -291,21 +320,29 @@ OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr, { return OC_STACK_INVALID_PARAM; } - uint16_t port = 0; + uint16_t securePort = 0; if (resourcePtr->resourceProperties & OC_SECURE) { - if (GetSecurePortInfo(devAddr, &port) != OC_STACK_OK) + if (GetSecurePortInfo(devAddr, &securePort) != OC_STACK_OK) { - port = 0; + securePort = 0; } } if (rdResponse) { - port = devAddr->port; + securePort = devAddr->port; + } + + uint16_t tcpPort = 0; +#ifdef TCP_ADAPTER + if (GetTCPPortInfo(devAddr, &tcpPort) != OC_STACK_OK) + { + tcpPort = 0; } +#endif - OCDiscoveryPayloadAddResource(payload, resourcePtr, port); + OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort); return OC_STACK_OK; } @@ -443,6 +480,9 @@ OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult) case OC_EH_RESOURCE_DELETED: result = OC_STACK_RESOURCE_DELETED; break; + case OC_EH_CHANGED: + result = OC_STACK_RESOURCE_CHANGED; + break; case OC_EH_RESOURCE_NOT_FOUND: result = OC_STACK_NO_RESOURCE; break; @@ -669,8 +709,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"); @@ -718,13 +756,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; @@ -739,8 +770,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); @@ -749,8 +779,10 @@ 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); + discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES); + VERIFY_NON_NULL(discPayload->type->value, 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); @@ -836,15 +868,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); } } } @@ -908,19 +949,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. "); } } @@ -953,7 +994,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 @@ -1017,7 +1059,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) @@ -1097,6 +1140,9 @@ HandleResourceWithEntityHandler (OCServerRequest *request, { OIC_LOG(INFO, TAG, "Removed observer successfully"); request->observeResult = OC_STACK_OK; + // There should be no observe option header for de-registration response. + // Set as an invalid value here so we can detect it later and remove the field in response. + request->observationOption = MAX_SEQUENCE_NUMBER + 1; } else { @@ -1151,7 +1197,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); @@ -1308,8 +1355,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) @@ -1325,12 +1375,84 @@ static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info) if (info.types) { savedDeviceInfo.types = CloneOCStringLL(info.types); + OCStringLL *type = info.types; + bool found = false; + while (type) + { + if (type && type->value && 0 == strcmp(type->value, OC_RSRVD_RESOURCE_TYPE_DEVICE)) + { + found = true; + } + type = type->next; + } + if (!found) + { + // Append the oic.wk.d at the start of rt link parameter value. + OCStringLL *dest = (OCStringLL*)OICCalloc (1, sizeof (OCStringLL)); + if (!dest) + { + DeleteDeviceInfo(); + return OC_STACK_NO_MEMORY; + } + dest->value = OICStrdup (OC_RSRVD_RESOURCE_TYPE_DEVICE); + if (!dest->value) + { + DeleteDeviceInfo(); + return OC_STACK_NO_MEMORY; + } + dest->next = savedDeviceInfo.types; + savedDeviceInfo.types = dest; + } if(!savedDeviceInfo.types && info.types) { DeleteDeviceInfo(); 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; } diff --git a/resource/csdk/stack/src/ocserverrequest.c b/resource/csdk/stack/src/ocserverrequest.c index 82631009f..75419d2f5 100644 --- a/resource/csdk/stack/src/ocserverrequest.c +++ b/resource/csdk/stack/src/ocserverrequest.c @@ -22,6 +22,7 @@ #include "ocstack.h" #include "ocserverrequest.h" #include "ocresourcehandler.h" +#include "ocobserve.h" #include "oic_malloc.h" #include "oic_string.h" #include "ocpayload.h" @@ -362,7 +363,8 @@ OCStackResult FormOCEntityHandlerRequest( uint8_t numVendorOptions, OCHeaderOption * vendorOptions, OCObserveAction observeAction, - OCObservationId observeID) + OCObservationId observeID, + uint16_t messageID) { if (entityHandlerRequest) { @@ -373,6 +375,7 @@ OCStackResult FormOCEntityHandlerRequest( entityHandlerRequest->query = queryBuf; entityHandlerRequest->obsInfo.action = observeAction; entityHandlerRequest->obsInfo.obsId = observeID; + entityHandlerRequest->messageID = messageID; if(payload && payloadSize) { @@ -419,49 +422,64 @@ 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_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 +513,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 +533,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) @@ -527,13 +548,13 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse) } char rspToken[CA_MAX_TOKEN_LEN + 1] = {}; - 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) + if((serverRequest->observeResult == OC_STACK_OK)&& + (serverRequest->observationOption != MAX_SEQUENCE_NUMBER + 1)) { responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1; } @@ -752,7 +773,6 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse) (OCRepPayload*)newPayload); } - (serverRequest->numResponses)--; if(serverRequest->numResponses == 0) @@ -773,4 +793,3 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse) exit: return stackRet; } - diff --git a/resource/csdk/stack/src/ocstack.c b/resource/csdk/stack/src/ocstack.c index 5ca4debb2..2af30826e 100644 --- a/resource/csdk/stack/src/ocstack.c +++ b/resource/csdk/stack/src/ocstack.c @@ -51,6 +51,7 @@ #include "logger.h" #include "ocserverrequest.h" #include "secureresourcemanager.h" +#include "psinterface.h" #include "doxmresource.h" #include "cacommon.h" #include "cainterface.h" @@ -132,10 +133,6 @@ OCDeviceEntityHandler defaultDeviceHandler; void* defaultDeviceHandlerCallbackParameter = NULL; static const char COAP_TCP[] = "coap+tcp:"; -//#ifdef DIRECT_PAIRING -OCDirectPairingCB gDirectpairingCallback = NULL; -//#endif - //----------------------------------------------------------------------------- // Macros //----------------------------------------------------------------------------- @@ -523,7 +520,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; @@ -574,7 +572,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; @@ -622,6 +621,8 @@ OCStackResult CAToOCStackResult(CAResponseResult_t caCode) ret = OC_STACK_RESOURCE_DELETED; break; case CA_CHANGED: + ret = OC_STACK_RESOURCE_CHANGED; + break; case CA_CONTENT: case CA_VALID: ret = OC_STACK_OK; @@ -1128,7 +1129,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 = MAX_SEQUENCE_NUMBER + 1; CopyEndpointToDevAddr(endPoint, &response.devAddr); FixUpClientResponse(&response); response.resourceUri = responseInfo->info.resourceUri; @@ -1275,6 +1276,7 @@ void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* resp if (cbNode->method == OC_REST_OBSERVE && response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER && + cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER && response.sequenceNumber <= cbNode->sequenceNumber) { OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d", @@ -1353,7 +1355,7 @@ void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* resp { OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET"); SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY, - CA_MSG_RESET, 0, NULL, NULL, 0, NULL); + CA_MSG_RESET, 0, NULL, NULL, 0, NULL); } } @@ -1796,7 +1798,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); @@ -2039,7 +2041,7 @@ OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlag VERIFY_SUCCESS(result, OC_STACK_OK); #ifdef TCP_ADAPTER - CARegisterKeepAliveHandler(HandleKeepAliveConnCB, HandleKeepAliveDisconnCB); + CARegisterKeepAliveHandler(HandleKeepAliveConnCB); #endif #ifdef WITH_PRESENCE @@ -2294,7 +2296,15 @@ static OCStackResult ParseRequestUri(const char *fullUri, { colon = close + 1; } - adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP); + + if (istcp) + { + adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP); + } + else + { + adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP); + } flags = (OCTransportFlags)(flags | OC_IP_USE_V6); } else @@ -2306,14 +2316,15 @@ static OCStackResult ParseRequestUri(const char *fullUri, end = (colon && colon < slash) ? colon : slash; if (istcp) - { // coap over tcp + { + // coap over tcp adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP); } else { adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP); - flags = (OCTransportFlags)(flags | OC_IP_USE_V4); } + flags = (OCTransportFlags)(flags | OC_IP_USE_V4); } else { // MAC address @@ -2724,9 +2735,11 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption case OC_REST_OBSERVE: case OC_REST_OBSERVE_ALL: - OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", - clientCB->requestUri); - if (qos != OC_HIGH_QOS) + OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri); + + CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint); + + if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS) { FindAndDeleteClientCB(clientCB); break; @@ -2746,7 +2759,6 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption requestInfo.info.numOptions = numOptions + 1; requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri); - CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint); ret = OCSendRequest(&endpoint, &requestInfo); @@ -3050,8 +3062,6 @@ OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo) { return OC_STACK_INVALID_PARAM; } - deleteResourceType(resource->rsrcType); - resource->rsrcType = NULL; while (type) { @@ -3911,16 +3921,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"); @@ -3935,9 +3936,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 @@ -4014,6 +4014,7 @@ OCStackResult initResources() if(result == OC_STACK_OK) { + CreateResetProfile(); result = OCCreateResource(&deviceResource, OC_RSRVD_RESOURCE_TYPE_DEVICE, OC_RSRVD_INTERFACE_DEFAULT, @@ -4575,3 +4576,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; + } +} diff --git a/resource/csdk/stack/src/oickeepalive.c b/resource/csdk/stack/src/oickeepalive.c index 8063f2b31..c94bb8572 100644 --- a/resource/csdk/stack/src/oickeepalive.c +++ b/resource/csdk/stack/src/oickeepalive.c @@ -716,31 +716,31 @@ OCStackResult RemoveKeepAliveEntry(const CAEndpoint_t *endpoint) return OC_STACK_OK; } -void HandleKeepAliveConnCB(const CAEndpoint_t *endpoint) +void HandleKeepAliveConnCB(const CAEndpoint_t *endpoint, bool isConnected) { VERIFY_NON_NULL_NR(endpoint, FATAL); - OIC_LOG(DEBUG, TAG, "Received the connected device information from CA"); - - // Send discover message to find ping resource - OCCallbackData pingData = { .cb = PingRequestCallback }; - OCDevAddr devAddr = { .adapter = OC_ADAPTER_TCP }; - CopyEndpointToDevAddr(endpoint, &devAddr); - - OCDoResource(NULL, OC_REST_DISCOVER, KEEPALIVE_RESOURCE_URI, &devAddr, NULL, - OC_ADAPTER_TCP, OC_HIGH_QOS, &pingData, NULL, 0); -} - -void HandleKeepAliveDisconnCB(const CAEndpoint_t *endpoint) -{ - VERIFY_NON_NULL_NR(endpoint, FATAL); + if (isConnected) + { + OIC_LOG(DEBUG, TAG, "Received the connected device information from CA"); - OIC_LOG(DEBUG, TAG, "Received the disconnected device information from CA"); + // Send discover message to find ping resource + OCCallbackData pingData = { .cb = PingRequestCallback }; + OCDevAddr devAddr = { .adapter = OC_ADAPTER_TCP }; + CopyEndpointToDevAddr(endpoint, &devAddr); - OCStackResult result = RemoveKeepAliveEntry(endpoint); - if(result != OC_STACK_OK) + OCDoResource(NULL, OC_REST_DISCOVER, KEEPALIVE_RESOURCE_URI, &devAddr, NULL, + OC_ADAPTER_TCP, OC_HIGH_QOS, &pingData, NULL, 0); + } + else { - OIC_LOG(ERROR, TAG, "Failed to remove entry"); - return; + OIC_LOG(DEBUG, TAG, "Received the disconnected device information from CA"); + + OCStackResult result = RemoveKeepAliveEntry(endpoint); + if(result != OC_STACK_OK) + { + OIC_LOG(ERROR, TAG, "Failed to remove entry"); + return; + } } } diff --git a/resource/csdk/stack/src/rdpayload.c b/resource/csdk/stack/src/rdpayload.c index 03788522d..97828e6a7 100644 --- a/resource/csdk/stack/src/rdpayload.c +++ b/resource/csdk/stack/src/rdpayload.c @@ -30,20 +30,20 @@ #define CBOR_ROOT_ARRAY_LENGTH 1 -static CborError OCTagsPayloadToCbor(OCTagsPayload *tags, CborEncoder *setMap); -static CborError OCLinksPayloadToCbor(OCLinksPayload *rtPtr, CborEncoder *setMap); +static int64_t OCTagsPayloadToCbor(OCTagsPayload *tags, CborEncoder *setMap); +static int64_t OCLinksPayloadToCbor(OCLinksPayload *rtPtr, CborEncoder *setMap); +static int64_t ConditionalAddTextStringToMap(CborEncoder* map, const char* key, const char *value); +static int64_t ConditionalAddIntToMap(CborEncoder *map, const char *tags, const uint64_t *value); +static int64_t AddStringLLToMap(CborEncoder *map, const char *tag, const OCStringLL *value); static CborError OCTagsCborToPayload(CborValue *tagsMap, OCTagsPayload **tagsPayload); static CborError OCLinksCborToPayload(CborValue *linksArray, OCLinksPayload **linksPayload); static CborError FindStringInMap(const CborValue *map, const char *tags, char **value); static CborError FindIntInMap(const CborValue *map, const char *tags, uint64_t *value); static CborError FindStringLLInMap(const CborValue *linksMap, const char *tag, OCStringLL **links); -static CborError ConditionalAddTextStringToMap(CborEncoder* map, const char* key, const char *value); -static CborError ConditionalAddIntToMap(CborEncoder *map, const char *tags, const uint64_t *value); -static CborError AddStringLLToMap(CborEncoder *map, const char *tag, const OCStringLL *value); -CborError OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, size_t *size) +int64_t OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, size_t *size) { - CborError cborEncoderResult = CborErrorIO; + int64_t cborEncoderResult = CborErrorIO; int flags = 0; CborEncoder encoder; VERIFY_PARAM_NON_NULL(TAG, rdPayload, "Invalid input parameter rdPayload"); @@ -55,52 +55,60 @@ CborError OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, s if (rdPayload->rdDiscovery) { CborEncoder map; - cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength); + cborEncoderResult |= cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create discovery map"); - cborEncoderResult = ConditionalAddTextStringToMap(&map, OC_RSRVD_DEVICE_NAME, + cborEncoderResult |= ConditionalAddTextStringToMap(&map, OC_RSRVD_DEVICE_NAME, rdPayload->rdDiscovery->n.deviceName); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_DEVICE_NAME in map"); - cborEncoderResult = ConditionalAddTextStringToMap(&map, OC_RSRVD_DEVICE_ID, + cborEncoderResult |= ConditionalAddTextStringToMap(&map, OC_RSRVD_DEVICE_ID, (char *)rdPayload->rdDiscovery->di.id); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_DEVICE_ID in map"); { uint64_t value = rdPayload->rdDiscovery->sel; - cborEncoderResult = ConditionalAddIntToMap(&map, OC_RSRVD_RD_DISCOVERY_SEL, &value); + cborEncoderResult |= ConditionalAddIntToMap(&map, OC_RSRVD_RD_DISCOVERY_SEL, &value); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add RD_DISCOVERY_SEL in map"); } - cborEncoderResult = cbor_encoder_close_container(&encoder, &map); + cborEncoderResult |= cbor_encoder_close_container(&encoder, &map); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed closing discovery map"); } else if (rdPayload->rdPublish) { CborEncoder colArray; - cborEncoderResult = cbor_encoder_create_array(&encoder, &colArray, CborIndefiniteLength); + cborEncoderResult |= cbor_encoder_create_array(&encoder, &colArray, CborIndefiniteLength); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create collection array"); OCResourceCollectionPayload *rdPublish = rdPayload->rdPublish; while (rdPublish) { - cborEncoderResult = OCTagsPayloadToCbor(rdPublish->tags, &colArray); + cborEncoderResult |= OCTagsPayloadToCbor(rdPublish->tags, &colArray); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed adding tags payload"); - cborEncoderResult = OCLinksPayloadToCbor(rdPublish->setLinks, &colArray); + cborEncoderResult |= OCLinksPayloadToCbor(rdPublish->setLinks, &colArray); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed adding setLinks payload"); rdPublish = rdPublish->next; } - cborEncoderResult = cbor_encoder_close_container(&encoder, &colArray); + cborEncoderResult |= cbor_encoder_close_container(&encoder, &colArray); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed closing collection array"); } else { CborEncoder map; - cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength); + cborEncoderResult |= cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed entering discovery map"); - cborEncoderResult = cbor_encoder_close_container(&encoder, &map); + cborEncoderResult |= cbor_encoder_close_container(&encoder, &map); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed closing discovery map"); } - *size = encoder.ptr - outPayload; + + if (cborEncoderResult == CborErrorOutOfMemory) + { + *size += encoder.ptr - encoder.end; + } + else + { + *size = encoder.ptr - outPayload; + } return cborEncoderResult; @@ -109,100 +117,101 @@ exit: return cborEncoderResult; } -static CborError OCTagsPayloadToCbor(OCTagsPayload *tags, CborEncoder *setMap) +static int64_t OCTagsPayloadToCbor(OCTagsPayload *tags, CborEncoder *setMap) { CborEncoder tagsMap; - CborError cborEncoderResult = cbor_encoder_create_map(setMap, &tagsMap, CborIndefiniteLength); + int64_t cborEncoderResult = CborNoError; + cborEncoderResult |= cbor_encoder_create_map(setMap, &tagsMap, CborIndefiniteLength); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create tags map"); - cborEncoderResult = ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DEVICE_NAME, tags->n.deviceName); + cborEncoderResult |= ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DEVICE_NAME, tags->n.deviceName); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_DEVICE_NAME in tags map"); - cborEncoderResult = ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DEVICE_ID, + cborEncoderResult |= ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DEVICE_ID, (char *)tags->di.id); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_DEVICE_ID in tags map"); - cborEncoderResult = ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_RTS, tags->rts); + cborEncoderResult |= ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_RTS, tags->rts); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_RTS in tags map"); - cborEncoderResult = ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DREL, tags->drel); + cborEncoderResult |= ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DREL, tags->drel); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_DREL in tags map"); - cborEncoderResult = ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_BASE_URI, tags->baseURI); + cborEncoderResult |= ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_BASE_URI, tags->baseURI); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_BASE_URI in tags map"); { uint64_t value = tags->bitmap; - cborEncoderResult = ConditionalAddIntToMap(&tagsMap, OC_RSRVD_BITMAP, &value); + cborEncoderResult |= ConditionalAddIntToMap(&tagsMap, OC_RSRVD_BITMAP, &value); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_BITMAP in tags map"); value = tags->port; - cborEncoderResult = ConditionalAddIntToMap(&tagsMap, OC_RSRVD_HOSTING_PORT, &value); + cborEncoderResult |= ConditionalAddIntToMap(&tagsMap, OC_RSRVD_HOSTING_PORT, &value); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_HOSTING_PORT in tags map"); value = tags->ins; - cborEncoderResult = ConditionalAddIntToMap(&tagsMap, OC_RSRVD_INS, &value); + cborEncoderResult |= ConditionalAddIntToMap(&tagsMap, OC_RSRVD_INS, &value); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_INS in tags map"); value = tags->ttl; - cborEncoderResult = ConditionalAddIntToMap(&tagsMap, OC_RSRVD_TTL, &value); + cborEncoderResult |= ConditionalAddIntToMap(&tagsMap, OC_RSRVD_TTL, &value); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_TTL in tags map"); } - cborEncoderResult = cbor_encoder_close_container(setMap, &tagsMap); + cborEncoderResult |= cbor_encoder_close_container(setMap, &tagsMap); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close container"); exit: return cborEncoderResult; } -static CborError OCLinksPayloadToCbor(OCLinksPayload *rtPtr, CborEncoder *setMap) +static int64_t OCLinksPayloadToCbor(OCLinksPayload *rtPtr, CborEncoder *setMap) { CborEncoder linksArray; - CborError cborEncoderResult; + int64_t cborEncoderResult = CborNoError; - cborEncoderResult = cbor_encoder_create_array(setMap, &linksArray, CborIndefiniteLength); + cborEncoderResult |= cbor_encoder_create_array(setMap, &linksArray, CborIndefiniteLength); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create Links array"); while (rtPtr) { CborEncoder linksMap; - cborEncoderResult = cbor_encoder_create_map(&linksArray, &linksMap, CborIndefiniteLength); + cborEncoderResult |= cbor_encoder_create_map(&linksArray, &linksMap, CborIndefiniteLength); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create Links map"); - cborEncoderResult = ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_HREF, rtPtr->href); + cborEncoderResult |= ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_HREF, rtPtr->href); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_HREF in Links map"); - cborEncoderResult = ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_REL, rtPtr->rel); + cborEncoderResult|= ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_REL, rtPtr->rel); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_REL in Links map"); - cborEncoderResult = ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_TITLE, rtPtr->title); + cborEncoderResult |= ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_TITLE, rtPtr->title); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_TITLE in Links map"); - cborEncoderResult = ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_URI, rtPtr->uri); + cborEncoderResult |= ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_URI, rtPtr->uri); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_URI in Links map"); - cborEncoderResult = AddStringLLToMap(&linksMap, OC_RSRVD_RESOURCE_TYPE, rtPtr->rt); + cborEncoderResult |= AddStringLLToMap(&linksMap, OC_RSRVD_RESOURCE_TYPE, rtPtr->rt); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_RT in Links map"); - cborEncoderResult = AddStringLLToMap(&linksMap, OC_RSRVD_INTERFACE, rtPtr->itf); + cborEncoderResult |= AddStringLLToMap(&linksMap, OC_RSRVD_INTERFACE, rtPtr->itf); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_ITF in Links map"); - cborEncoderResult = AddStringLLToMap(&linksMap, OC_RSRVD_MEDIA_TYPE, rtPtr->mt); + cborEncoderResult |= AddStringLLToMap(&linksMap, OC_RSRVD_MEDIA_TYPE, rtPtr->mt); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_MT in Links map"); { uint64_t value = rtPtr->ins; - cborEncoderResult = ConditionalAddIntToMap(&linksMap, OC_RSRVD_INS, &value); + cborEncoderResult |= ConditionalAddIntToMap(&linksMap, OC_RSRVD_INS, &value); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add OC_RSRVD_INS in Links map"); } - cborEncoderResult = cbor_encoder_close_container(&linksArray, &linksMap); + cborEncoderResult |= cbor_encoder_close_container(&linksArray, &linksMap); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed closing Links map"); rtPtr = rtPtr->next; } - cborEncoderResult = cbor_encoder_close_container(setMap, &linksArray); + cborEncoderResult |= cbor_encoder_close_container(setMap, &linksArray); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed closing links array"); exit: @@ -466,48 +475,48 @@ exit: return cborFindResult; } -static CborError AddTextStringToMap(CborEncoder* map, const char* key, const char* value) +static int64_t AddTextStringToMap(CborEncoder* map, const char* key, const char* value) { - CborError err = cbor_encode_text_string(map, key, strlen(key)); + int64_t err = cbor_encode_text_string(map, key, strlen(key)); VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting key value"); - err = cbor_encode_text_string(map, value, strlen(value)); + err |= cbor_encode_text_string(map, value, strlen(value)); exit: return err; } -static CborError ConditionalAddTextStringToMap(CborEncoder* map, const char* key, const char* value) +static int64_t ConditionalAddTextStringToMap(CborEncoder* map, const char* key, const char* value) { return value ? AddTextStringToMap(map, key, value) : CborNoError; } -static CborError ConditionalAddIntToMap(CborEncoder *map, const char *tags, const uint64_t *value) +static int64_t ConditionalAddIntToMap(CborEncoder *map, const char *tags, const uint64_t *value) { - CborError err = CborNoError; + int64_t err = CborNoError; if (*value) { - err = cbor_encode_text_string(map, tags, strlen(tags)); + err |= cbor_encode_text_string(map, tags, strlen(tags)); VERIFY_CBOR_SUCCESS(TAG, err, "failed setting value"); - err = cbor_encode_uint(map, *value); + err |= cbor_encode_uint(map, *value); } exit: return err; } -static CborError AddStringLLToMap(CborEncoder *map, const char *tag, const OCStringLL *strType) +static int64_t AddStringLLToMap(CborEncoder *map, const char *tag, const OCStringLL *strType) { CborEncoder array; - CborError cborEncoderResult; - cborEncoderResult = cbor_encode_text_string(map, tag, strlen(tag)); + int64_t cborEncoderResult = CborNoError; + cborEncoderResult |= cbor_encode_text_string(map, tag, strlen(tag)); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed encoding string tag name"); - cborEncoderResult = cbor_encoder_create_array(map, &array, CborIndefiniteLength); + cborEncoderResult |= cbor_encoder_create_array(map, &array, CborIndefiniteLength); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed creating stringLL array"); while (strType) { - cborEncoderResult = cbor_encode_text_string(&array, strType->value, strlen(strType->value)); + cborEncoderResult |= cbor_encode_text_string(&array, strType->value, strlen(strType->value)); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed encoding string value"); strType = strType->next; } - cborEncoderResult = cbor_encoder_close_container(map, &array); + cborEncoderResult |= cbor_encoder_close_container(map, &array); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed closing string array"); exit: return cborEncoderResult; diff --git a/resource/csdk/stack/test/SConscript b/resource/csdk/stack/test/SConscript index 507f011f5..a011dfd91 100644 --- a/resource/csdk/stack/test/SConscript +++ b/resource/csdk/stack/test/SConscript @@ -18,12 +18,15 @@ # #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -Import('env') import os import os.path -stacktest_env = env.Clone() + +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +stacktest_env = gtest_env.Clone() src_dir = stacktest_env.get('SRC_DIR') +target_os = stacktest_env.get('TARGET_OS') ###################################################################### # Build flags @@ -39,32 +42,30 @@ stacktest_env.PrependUnique(CPPPATH = [ '../../connectivity/external/inc', '../../extlibs/cjson', '../../../oc_logger/include', - '#extlibs/gtest/gtest-1.7.0/include' ]) - -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', +if target_os not in ['windows']: + stacktest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) +stacktest_env.AppendUnique(LIBPATH = [stacktest_env.get('BUILD_DIR')]) +stacktest_env.PrependUnique(LIBS = ['octbstack', 'ocsrm', 'connectivity_abstraction', 'coap', 'gtest', 'gtest_main']) -target_os = env.get('TARGET_OS') if target_os != 'darwin': stacktest_env.PrependUnique(LIBS = ['oc_logger']) - -if env.get('SECURED') == '1': +if stacktest_env.get('SECURED') == '1': stacktest_env.AppendUnique(LIBS = ['tinydtls']) -if env.get('LOGGING'): +if stacktest_env.get('LOGGING'): stacktest_env.AppendUnique(CPPDEFINES = ['TB_LOG']) +if target_os not in ['msys_nt', 'windows']: + stacktest_env.PrependUnique(LIBS = ['m']) + stacktest_env.PrependUnique(LIBS = ['pthread']) + ###################################################################### # Source files and Targets ###################################################################### @@ -73,10 +74,10 @@ cbortests = stacktest_env.Program('cbortests', ['cbortests.cpp']) Alias("test", [stacktests, cbortests]) -env.AppendTarget('test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': + +stacktest_env.AppendTarget('test') +if stacktest_env.get('TEST') == '1': + if target_os in ['linux']: from tools.scons.RunTest import * run_test(stacktest_env, 'resource_csdk_stack_test.memcheck', diff --git a/resource/csdk/stack/test/linux/occlient.c b/resource/csdk/stack/test/linux/occlient.c index 40132fd58..d64643994 100644 --- a/resource/csdk/stack/test/linux/occlient.c +++ b/resource/csdk/stack/test/linux/occlient.c @@ -60,7 +60,7 @@ int main() { } /* Start a discovery query*/ - char szQueryUri[64] = { 0 }; + char szQueryUri[MAX_QUERY_LENGTH] = { 0 }; strcpy(szQueryUri, OC_EXPLICIT_DEVICE_DISCOVERY_URI); if (OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, 0, 0, 0) != OC_STACK_OK) { diff --git a/resource/csdk/stack/test/stacktests.cpp b/resource/csdk/stack/test/stacktests.cpp index a5b9fe4dc..74a5a92ea 100644 --- a/resource/csdk/stack/test/stacktests.cpp +++ b/resource/csdk/stack/test/stacktests.cpp @@ -85,10 +85,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, @@ -351,7 +352,7 @@ TEST(StackDiscovery, DISABLED_DoResourceDeviceDiscovery) InitStack(OC_CLIENT); /* Start a discovery query*/ - char szQueryUri[64] = { 0 }; + char szQueryUri[MAX_QUERY_LENGTH] = { 0 }; strcpy(szQueryUri, OC_RSRVD_WELL_KNOWN_URI); cbData.cb = asyncDoResourcesCallback; cbData.context = (void*)DEFAULT_CONTEXT_VALUE; @@ -393,7 +394,7 @@ TEST(StackResource, DISABLED_UpdateResourceNullURI) InitStack(OC_CLIENT); /* Start a discovery query*/ - char szQueryUri[64] = { 0 }; + char szQueryUri[MAX_QUERY_LENGTH] = { 0 }; strcpy(szQueryUri, OC_RSRVD_WELL_KNOWN_URI); cbData.cb = asyncDoResourcesCallback; cbData.context = (void*)DEFAULT_CONTEXT_VALUE; @@ -1680,17 +1681,17 @@ TEST(PODTests, OCCallbackData) 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) @@ -1725,7 +1726,7 @@ TEST(StackResource, MultipleResourcesDiscovery) NULL, OC_DISCOVERABLE|OC_OBSERVABLE)); /* Start a discovery query*/ - char szQueryUri[256] = "/oic/res?if=oic.if.ll"; + char szQueryUri[MAX_QUERY_LENGTH] = "/oic/res?if=oic.if.ll"; OCCallbackData cbData; cbData.cb = discoveryCallback; cbData.context = (void*)DEFAULT_CONTEXT_VALUE; diff --git a/resource/examples/SConscript b/resource/examples/SConscript index 9fad82842..c5db21293 100644 --- a/resource/examples/SConscript +++ b/resource/examples/SConscript @@ -46,11 +46,16 @@ if target_os not in ['windows', 'winrt']: # 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': - examples_env.AppendUnique(LIBS = ['-lpthread']) + examples_env.AppendUnique(LIBS = ['pthread']) examples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) examples_env.AppendUnique(RPATH = [env.get('BUILD_DIR')]) -examples_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap']) +examples_env.PrependUnique(LIBS = ['coap']) +examples_env.AppendUnique(LIBS = ['connectivity_abstraction']) +examples_env.AppendUnique(LIBS = ['oc_logger']) +examples_env.AppendUnique(LIBS = ['octbstack']) +examples_env.AppendUnique(LIBS = ['oc']) + if env.get('SECURED') == '1': examples_env.AppendUnique(LIBS = ['tinydtls']) @@ -86,11 +91,14 @@ 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') +directpairingclient = examples_env.Program('directpairingclient', 'directpairingclient.cpp') 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') +directpairingdat = examples_env.Install(env.get('BUILD_DIR') + '/resource/examples/', + env.get('SRC_DIR') + '/resource/examples/' + 'oic_svr_db_client_directpairing.dat') Alias("examples", [simpleserver, simpleclient, simpleserverHQ, simpleclientHQ, fridgeserver, fridgeclient, @@ -100,7 +108,7 @@ Alias("examples", [simpleserver, simpleclient, groupserver, groupclient, lightserver, devicediscoveryserver, devicediscoveryclient, - threadingsample, - serverjson, clientjson + threadingsample, directpairingclient, + serverjson, clientjson, directpairingdat ]) env.AppendTarget('examples') diff --git a/resource/examples/devicediscoveryserver.cpp b/resource/examples/devicediscoveryserver.cpp index 2112ae66d..dba1515a5 100644 --- a/resource/examples/devicediscoveryserver.cpp +++ b/resource/examples/devicediscoveryserver.cpp @@ -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 index 000000000..6ab04fe1c --- /dev/null +++ b/resource/examples/directpairingclient.cpp @@ -0,0 +1,411 @@ +/* ***************************************************************** + * + * 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> +#include <unistd.h> +#include <string> +#include <map> +#include <cstdlib> +#include <pthread.h> +#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; +} diff --git a/resource/examples/fridgeserver.cpp b/resource/examples/fridgeserver.cpp index dbc91eae1..556b34c72 100644 --- a/resource/examples/fridgeserver.cpp +++ b/resource/examples/fridgeserver.cpp @@ -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) { diff --git a/resource/examples/garageclient.cpp b/resource/examples/garageclient.cpp index 45e59b49f..9fbc4463d 100644 --- a/resource/examples/garageclient.cpp +++ b/resource/examples/garageclient.cpp @@ -164,7 +164,7 @@ void printRepresentation(const OCRepresentation& rep) // callback handler on PUT request void onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode) { - if(eCode == SUCCESS_RESPONSE) + if(eCode == SUCCESS_RESPONSE || eCode == OC_STACK_RESOURCE_CHANGED) { std::cout << "PUT request was successful" << std::endl; diff --git a/resource/examples/oic_svr_db_client.dat b/resource/examples/oic_svr_db_client.dat Binary files differindex 6feb47306..3c93b283c 100644 --- a/resource/examples/oic_svr_db_client.dat +++ b/resource/examples/oic_svr_db_client.dat diff --git a/resource/examples/oic_svr_db_client.json b/resource/examples/oic_svr_db_client.json index 5052bd118..792c3b184 100644 --- a/resource/examples/oic_svr_db_client.json +++ b/resource/examples/oic_svr_db_client.json @@ -8,38 +8,32 @@ {
"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": ""
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
},
{
"href": "/oic/ad",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.ad"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/acl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.acl"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 2
@@ -50,14 +44,14 @@ {
"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": 2
@@ -83,7 +77,7 @@ "deviceuuid": "32323232-3232-3232-3232-323232323232",
"devowneruuid": "32323232-3232-3232-3232-323232323232",
"rowneruuid": "32323232-3232-3232-3232-323232323232",
- "dpc": false
+ "x.org.iotivity.dpc": false
},
"cred": {
"creds": [
diff --git a/resource/examples/oic_svr_db_client_directpairing.dat b/resource/examples/oic_svr_db_client_directpairing.dat Binary files differnew file mode 100644 index 000000000..146d24033 --- /dev/null +++ b/resource/examples/oic_svr_db_client_directpairing.dat diff --git a/resource/examples/oic_svr_db_client_directpairing.json b/resource/examples/oic_svr_db_client_directpairing.json new file mode 100644 index 000000000..7f8e9b907 --- /dev/null +++ b/resource/examples/oic_svr_db_client_directpairing.json @@ -0,0 +1,82 @@ +{
+ "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" : "64706169-7269-6e67-4465-765555494430"
+ },
+ "pstat": {
+ "isop": false,
+ "deviceuuid": "64706169-7269-6e67-4465-765555494430",
+ "rowneruuid": "64706169-7269-6e67-4465-765555494430",
+ "cm": 2,
+ "tm": 0,
+ "om": 3,
+ "sm": 3
+ },
+ "doxm": {
+ "oxms": [0],
+ "oxmsel": 0,
+ "sct": 1,
+ "owned": false,
+ "deviceuuid": "64706169-7269-6e67-4465-765555494430",
+ "devowneruuid": "",
+ "rowneruuid": "64706169-7269-6e67-4465-765555494430",
+ "x.org.iotivity.dpc": false
+ }
+}
diff --git a/resource/examples/oic_svr_db_server.dat b/resource/examples/oic_svr_db_server.dat Binary files differindex 6834a79f2..15eaaa637 100644 --- a/resource/examples/oic_svr_db_server.dat +++ b/resource/examples/oic_svr_db_server.dat diff --git a/resource/examples/oic_svr_db_server.json b/resource/examples/oic_svr_db_server.json index 921cc9de4..5ed46fa61 100644 --- a/resource/examples/oic_svr_db_server.json +++ b/resource/examples/oic_svr_db_server.json @@ -8,38 +8,32 @@ {
"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": ""
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
},
{
"href": "/oic/ad",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.ad"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/acl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.acl"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 2
@@ -50,14 +44,14 @@ {
"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": 2
@@ -68,8 +62,8 @@ {
"href": "/a/light",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 6
@@ -95,7 +89,7 @@ "deviceuuid": "31313131-3131-3131-3131-313131313131",
"devowneruuid": "32323232-3232-3232-3232-323232323232",
"rowneruuid": "31313131-3131-3131-3131-313131313131",
- "dpc": false
+ "x.org.iotivity.dpc": false
},
"cred": {
"creds": [
diff --git a/resource/examples/simpleclient.cpp b/resource/examples/simpleclient.cpp index 07d55f0db..fc0673a40 100644 --- a/resource/examples/simpleclient.cpp +++ b/resource/examples/simpleclient.cpp @@ -29,6 +29,8 @@ #include "OCPlatform.h" #include "OCApi.h" +#define maxSequenceNumber 0xFFFFFF + using namespace OC; static const char* SVR_DB_FILE_NAME = "./oic_svr_db_client.dat"; @@ -65,16 +67,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 != maxSequenceNumber + 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 +97,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 { @@ -122,7 +120,8 @@ void onPost2(const HeaderOptions& /*headerOptions*/, { try { - if(eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED) + if(eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED + || eCode == OC_STACK_RESOURCE_CHANGED) { std::cout << "POST request was successful" << std::endl; @@ -168,7 +167,8 @@ void onPost(const HeaderOptions& /*headerOptions*/, { try { - if(eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED) + if(eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED + || eCode == OC_STACK_RESOURCE_CHANGED) { std::cout << "POST request was successful" << std::endl; @@ -237,7 +237,7 @@ void onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, { try { - if(eCode == OC_STACK_OK) + if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CHANGED) { std::cout << "PUT request was successful" << std::endl; @@ -469,7 +469,7 @@ int main(int argc, char* argv[]) { OC::ModeType::Both, "0.0.0.0", 0, - OC::QualityOfService::LowQos, + OC::QualityOfService::HighQos, &ps }; diff --git a/resource/examples/simpleclientHQ.cpp b/resource/examples/simpleclientHQ.cpp index 86081f8df..a1377c79b 100644 --- a/resource/examples/simpleclientHQ.cpp +++ b/resource/examples/simpleclientHQ.cpp @@ -114,7 +114,7 @@ void onObserve(const HeaderOptions /*headerOptions*/, const OCRepresentation& re void onPost2(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode) { - if(eCode == SUCCESS_RESPONSE) + if(eCode == SUCCESS_RESPONSE || eCode == OC_STACK_RESOURCE_CHANGED) { std::cout << "POST request was successful" << std::endl; @@ -153,7 +153,7 @@ void onPost2(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep void onPost(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode) { - if(eCode == SUCCESS_RESPONSE) + if(eCode == SUCCESS_RESPONSE || eCode == OC_STACK_RESOURCE_CHANGED) { std::cout << "POST request was successful" << std::endl; diff --git a/resource/examples/simpleclientserver.cpp b/resource/examples/simpleclientserver.cpp index 939e5f14d..2c8f0acfd 100644 --- a/resource/examples/simpleclientserver.cpp +++ b/resource/examples/simpleclientserver.cpp @@ -51,7 +51,7 @@ private: std::cout <<"Clientside Put response to get was: "<<std::endl; std::cout <<"ErrorCode: "<<eCode <<std::endl; - if(eCode == 0) + if(eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CHANGED) { std::cout<<"Successful Put. Attributes sent were: "<<std::endl; diff --git a/resource/include/IClientWrapper.h b/resource/include/IClientWrapper.h index bfbb00f02..cd8387a37 100644 --- a/resource/include/IClientWrapper.h +++ b/resource/include/IClientWrapper.h @@ -23,7 +23,6 @@ #include <memory> #include <string> - #include <OCApi.h> namespace OC @@ -104,6 +103,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(){} }; } diff --git a/resource/include/InProcClientWrapper.h b/resource/include/InProcClientWrapper.h index 62830d57a..82485ad7a 100644 --- a/resource/include/InProcClientWrapper.h +++ b/resource/include/InProcClientWrapper.h @@ -81,6 +81,13 @@ namespace OC ObserveCallback callback; ObserveContext(ObserveCallback cb) : callback(cb){} }; + + struct DirectPairingContext + { + DirectPairingCallback callback; + DirectPairingContext(DirectPairingCallback cb) : callback(cb){} + + }; } class InProcClientWrapper : public IClientWrapper @@ -146,12 +153,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; diff --git a/resource/include/OCApi.h b/resource/include/OCApi.h index c0fdf93ef..a547b57ce 100644 --- a/resource/include/OCApi.h +++ b/resource/include/OCApi.h @@ -41,6 +41,7 @@ namespace OC class OCResource; class OCResourceRequest; class OCResourceResponse; + class OCDirectPairing; } // namespace OC namespace OC @@ -249,6 +250,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; @@ -275,6 +278,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 index 000000000..3f27b83af --- /dev/null +++ b/resource/include/OCDirectPairing.h @@ -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_ diff --git a/resource/include/OCHeaderOption.h b/resource/include/OCHeaderOption.h index 65ec176b3..519da7884 100644 --- a/resource/include/OCHeaderOption.h +++ b/resource/include/OCHeaderOption.h @@ -40,11 +40,17 @@ namespace OC * After creating instances of OCHeaderOptions, use setHeaderOptions API * (in OCResource.h) to set header Options. * NOTE: HeaderOptionID is an unsigned integer value which MUST be within - * range of 2048 to 3000 inclusive of lower and upper bound. + * range of 2048 to 3000 inclusive of lower and upper bound + * except for If-Match with empty(num : 1), If-None-Match(num : 5), + * Location-Path(num : 8), Location-Query(num : 20) option. * HeaderOptions instance creation fails if above condition is not satisfied. */ const uint16_t MIN_HEADER_OPTIONID = 2048; const uint16_t MAX_HEADER_OPTIONID = 3000; + const uint16_t IF_MATCH_OPTION_ID = 1; + const uint16_t IF_NONE_MATCH_OPTION_ID = 5; + const uint16_t LOCATION_PATH_OPTION_ID = 8; + const uint16_t LOCATION_QUERY_OPTION_ID = 20; class OCHeaderOption { @@ -60,7 +66,11 @@ namespace OC m_optionID(optionID), m_optionData(optionData) { - if(!(optionID >= MIN_HEADER_OPTIONID && optionID <= MAX_HEADER_OPTIONID)) + if (!(optionID >= MIN_HEADER_OPTIONID && optionID <= MAX_HEADER_OPTIONID) + && optionID != IF_MATCH_OPTION_ID + && optionID != IF_NONE_MATCH_OPTION_ID + && optionID != LOCATION_PATH_OPTION_ID + && optionID != LOCATION_QUERY_OPTION_ID) { throw OCException(OC::Exception::OPTION_ID_RANGE_INVALID); } diff --git a/resource/include/OCPlatform.h b/resource/include/OCPlatform.h index fefeb35a3..cec885515 100644 --- a/resource/include/OCPlatform.h +++ b/resource/include/OCPlatform.h @@ -515,45 +515,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, @@ -561,14 +561,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); } } diff --git a/resource/include/OCPlatform_impl.h b/resource/include/OCPlatform_impl.h index 6ad03d316..30ddeed36 100644 --- a/resource/include/OCPlatform_impl.h +++ b/resource/include/OCPlatform_impl.h @@ -37,6 +37,7 @@ #include "OCResourceRequest.h" #include "OCResourceResponse.h" #include "OCRepresentation.h" +#include "OCDirectPairing.h" #include "oc_logger.hpp" @@ -224,6 +225,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; diff --git a/resource/include/OCProvisioningManager.h b/resource/include/OCProvisioningManager.h index 0a949e36c..0638d99f7 100644 --- a/resource/include/OCProvisioningManager.h +++ b/resource/include/OCProvisioningManager.h @@ -268,6 +268,31 @@ namespace OC ResultCallBack resultCallback); /** + * API to remove device credential and ACL from all devices in subnet. + * + * @param resultCallback Callback provided by API user, callback will be called when + * credential revocation is finished. + * @param uuid Device uuid to be revoked. + * @param waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device + * discovery in seconds. + * @return ::OC_STACK_OK in case of success and other value otherwise. + */ + OCStackResult removeDeviceWithUuid(unsigned short waitTimeForOwnedDeviceDiscovery, + std::string uuid, + 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. diff --git a/resource/include/OCRepresentation.h b/resource/include/OCRepresentation.h index 4d1d24a99..9c61c32c5 100644 --- a/resource/include/OCRepresentation.h +++ b/resource/include/OCRepresentation.h @@ -131,6 +131,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 +143,8 @@ namespace OC void addResourceInterface(const std::string& str); + void addDataModelVersion(const std::string& str); + bool emptyData() const; int numberOfAttributes() const; @@ -445,6 +449,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; }; diff --git a/resource/include/OCResourceRequest.h b/resource/include/OCResourceRequest.h index e17e3a67d..a2e13c15f 100644 --- a/resource/include/OCResourceRequest.h +++ b/resource/include/OCResourceRequest.h @@ -51,6 +51,7 @@ namespace OC m_resourceUri{}, m_queryParameters{}, m_requestHandlerFlag{}, + m_messageID{}, m_representation{}, m_observationInfo{}, m_headerOptions{}, @@ -154,11 +155,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 +195,11 @@ namespace OC m_requestHandlerFlag = requestHandlerFlag; } + void setMessageID(int16_t messageID) + { + m_messageID = messageID; + } + void setObservationInfo(const ObservationInfo& observationInfo) { m_observationInfo = observationInfo; diff --git a/resource/include/OCSerialization.h b/resource/include/OCSerialization.h index c9526f151..aa154bc24 100644 --- a/resource/include/OCSerialization.h +++ b/resource/include/OCSerialization.h @@ -83,6 +83,23 @@ namespace OC StringLLToVector(res->types), StringLLToVector(res->interfaces) ))); + +#ifdef TCP_ADAPTER + if (res->tcpPort != 0) + { + OCDevAddr tcpDevAddr = m_devAddr; + tcpDevAddr.port = res->tcpPort; + tcpDevAddr.adapter = OC_ADAPTER_TCP; + m_resources.push_back(std::shared_ptr<OC::OCResource>( + new OC::OCResource(m_clientWrapper, tcpDevAddr, + std::string(res->uri), + std::string(payload->sid), + (res->bitmap & OC_OBSERVABLE) == OC_OBSERVABLE, + StringLLToVector(res->types), + StringLLToVector(res->interfaces) + ))); + } +#endif } res = res->next; } diff --git a/resource/include/OutOfProcClientWrapper.h b/resource/include/OutOfProcClientWrapper.h index a6fd165c8..85feb3c61 100644 --- a/resource/include/OutOfProcClientWrapper.h +++ b/resource/include/OutOfProcClientWrapper.h @@ -115,6 +115,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;} }; } diff --git a/resource/include/StringConstants.h b/resource/include/StringConstants.h index 526a0b9bf..4b9793804 100644 --- a/resource/include/StringConstants.h +++ b/resource/include/StringConstants.h @@ -60,7 +60,9 @@ namespace OC static const char GENERAL_JSON_PARSE_FAILED[] = "JSON Parser Error"; static const char RESOURCE_UNREG_FAILED[] = "Unregistering resource failed"; static const char OPTION_ID_RANGE_INVALID[] = - "Error: OptionID valid only from 2048 to 3000 inclusive."; + "Error: OptionID valid only If-Match(1), If-None-Match(5)," + "Location-Path(8), Location-Query(20)," + "and from 2048 to 3000 inclusive."; static const char NO_ERROR[] = "No Error"; static const char RESOURCE_CREATED[] = "Resource Created"; static const char RESOURCE_DELETED[] = "Resource Deleted"; diff --git a/resource/provisioning/examples/SConscript b/resource/provisioning/examples/SConscript index ceb52bf13..6d024247f 100644 --- a/resource/provisioning/examples/SConscript +++ b/resource/provisioning/examples/SConscript @@ -41,6 +41,7 @@ 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' diff --git a/resource/provisioning/examples/oic_svr_db_client.dat b/resource/provisioning/examples/oic_svr_db_client.dat Binary files differindex 781f65483..42249be6a 100644 --- a/resource/provisioning/examples/oic_svr_db_client.dat +++ b/resource/provisioning/examples/oic_svr_db_client.dat diff --git a/resource/provisioning/examples/oic_svr_db_client.json b/resource/provisioning/examples/oic_svr_db_client.json index fb3c60918..6b8e2b764 100644 --- a/resource/provisioning/examples/oic_svr_db_client.json +++ b/resource/provisioning/examples/oic_svr_db_client.json @@ -8,38 +8,32 @@ {
"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": ""
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
},
{
"href": "/oic/ad",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.ad"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/amacl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.amacl"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 2
@@ -50,22 +44,22 @@ {
"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": 2
}
]
},
"rowneruuid" : "61646D69-6E44-6576-6963-655575696430"
- },
+ },
"pstat": {
"isop": true,
"cm": 0,
@@ -81,7 +75,7 @@ "sct": 1,
"owned": true,
"deviceuuid": "61646D69-6E44-6576-6963-655575696430",
- "dpc": false,
+ "x.org.iotivity.dpc": false,
"devowneruuid": "61646D69-6E44-6576-6963-655575696430",
"rowneruuid": "61646D69-6E44-6576-6963-655575696430"
}
diff --git a/resource/provisioning/examples/provisioningclient.cpp b/resource/provisioning/examples/provisioningclient.cpp index b2c982523..c8eab51d7 100644 --- a/resource/provisioning/examples/provisioningclient.cpp +++ b/resource/provisioning/examples/provisioningclient.cpp @@ -36,9 +36,12 @@ #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) @@ -56,10 +59,16 @@ #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) { @@ -78,9 +87,11 @@ void printMenu() std::cout << " 6. Credential & ACL provisioning b/w two devices"<<std::endl; 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 << " 9. Remove Device using UUID"<<std::endl; + std::cout << " 10. Get Linked Devices"<<std::endl; + std::cout << " 11. Get Device Status"<<std::endl; + std::cout << " 12. Provision Direct-Pairing Configuration"<<std::endl; + std::cout << " 13. Exit loop"<<std::endl; } void moveTransferredDevice() @@ -263,19 +274,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 +362,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 +418,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->href ); + 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 (e.g. core.led): ", 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->href); + 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 interfnace[%d] Name (e.g. oic.if.baseline): ", 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 +519,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 +534,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 +547,10 @@ static int InputACL(OicSecAcl_t *acl) OICFree(temp_id); return 0; + +error: + DeleteACLList(acl); + return -1; } static int InputCredentials(Credential &cred) @@ -504,6 +606,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 }; @@ -816,7 +1108,28 @@ int main(void) } break; } - case 9: //Get Linked devices + case 9: //Remove Device using UUID + { + int index; + + if (0 != readDeviceNumber(pOwnedDevList, 1, &index)) break; + + std::cout << "Remove Device: "<< pOwnedDevList[index]->getDeviceID()<< std::endl; + + ask = 0; + + if (pOwnedDevList[index]->removeDeviceWithUuid(DISCOVERY_TIMEOUT, + pOwnedDevList[index]->getDeviceID(), + provisionCB) + != OC_STACK_OK) + { + ask = 1; + std::cout <<"removeDevice is failed"<< std::endl; + } + break; + } + + case 10: //Get Linked devices { UuidList_t linkedUuid; unsigned int devNum; @@ -861,7 +1174,7 @@ int main(void) } break; } - case 10: //Get device' status + case 11: //Get device' status { DeviceList_t unownedList, ownedList; @@ -889,7 +1202,37 @@ int main(void) break; } - case 11: + case 12: + { + 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 13: default: out = 1; break; diff --git a/resource/provisioning/src/OCProvisioningManager.cpp b/resource/provisioning/src/OCProvisioningManager.cpp index 8a2c07637..ed3457425 100644 --- a/resource/provisioning/src/OCProvisioningManager.cpp +++ b/resource/provisioning/src/OCProvisioningManager.cpp @@ -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); @@ -458,6 +458,45 @@ namespace OC return result; } + OCStackResult OCSecureResource::removeDeviceWithUuid(unsigned short waitTimeForOwnedDeviceDiscovery, + std::string uuid, + ResultCallBack resultCallback) + { + if (!resultCallback) + { + oclog() << "Result calback can't 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); + + OicUuid_t targetDev; + result = ConvertStrToUuid(uuid.c_str(), &targetDev); + if(OC_STACK_OK == result) + { + result = OCRemoveDeviceWithUuid(static_cast<void*>(context), waitTimeForOwnedDeviceDiscovery, + &targetDev, &OCSecureResource::callbackWrapper); + } + else + { + oclog() <<"Can not convert struuid to uuid"; + } + } + else + { + oclog() <<"Mutex not found"; + result = OC_STACK_ERROR; + } + return result; + } + OCStackResult OCSecureResource::getLinkedDevices(UuidList_t &uuidList) { OCStackResult result; @@ -465,7 +504,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 +527,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 +571,7 @@ namespace OC if (OC_STACK_OK == ConvertUuidToStr(&(devPtr->doxm->deviceID), &devID)) { deviceId << devID; + free(devID); } else { diff --git a/resource/provisioning/unittests/OCProvisioningTest.cpp b/resource/provisioning/unittests/OCProvisioningTest.cpp index 38e27bf5b..9e44e0667 100644 --- a/resource/provisioning/unittests/OCProvisioningTest.cpp +++ b/resource/provisioning/unittests/OCProvisioningTest.cpp @@ -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)); + } } diff --git a/resource/provisioning/unittests/SConscript b/resource/provisioning/unittests/SConscript index 35829608d..bca6b5e8e 100755 --- a/resource/provisioning/unittests/SConscript +++ b/resource/provisioning/unittests/SConscript @@ -18,14 +18,17 @@ # #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -Import('env') import os import os.path -provisiontests_env = env.Clone() +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +provisiontests_env = gtest_env.Clone() src_dir = provisiontests_env.get('SRC_DIR') -with_ra = env.get('WITH_RA') -with_ra_ibb = env.get('WITH_RA_IBB') +target_os = provisiontests_env.get('TARGET_OS') +with_ra = provisiontests_env.get('WITH_RA') +with_ra_ibb = provisiontests_env.get('WITH_RA_IBB') + ###################################################################### # Build flags ###################################################################### @@ -43,15 +46,15 @@ provisiontests_env.PrependUnique(CPPPATH = [ '../../csdk/ocsocket/include', '../../csdk/ocrandom/include', '../../csdk/logger/include', - '../../../extlibs/gtest/gtest-1.7.0/include', '../../../extlibs/hippomocks-master/HippoMocks', '../../../extlibs/hippomocks-master/HippoMocksTest' ]) -provisiontests_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) -provisiontests_env.AppendUnique(LIBS = ['-lpthread', '-ldl']) -provisiontests_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) -provisiontests_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs']) +if target_os not in ['windows']: + provisiontests_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) + provisiontests_env.AppendUnique(LIBS = ['-lpthread', '-ldl']) + +provisiontests_env.AppendUnique(LIBPATH = [provisiontests_env.get('BUILD_DIR')]) provisiontests_env.PrependUnique(LIBS = [ 'ocprovision', 'oc', @@ -73,15 +76,15 @@ else : if with_ra: provisiontests_env.AppendUnique(LIBS = ['ra_xmpp']) -if env.get('SECURED') == '1': +if provisiontests_env.get('SECURED') == '1': provisiontests_env.AppendUnique(LIBS = ['tinydtls']) provisiontests_env.AppendUnique(LIBS = ['timer']) -if env.get('DTLS_WITH_X509') == '1': +if provisiontests_env.get('DTLS_WITH_X509') == '1': provisiontests_env.AppendUnique(LIBS = ['CKManager']) provisiontests_env.AppendUnique(LIBS = ['asn1']) -if env.get('LOGGING'): +if provisiontests_env.get('LOGGING'): provisiontests_env.AppendUnique(CPPDEFINES = ['TB_LOG']) ###################################################################### @@ -91,22 +94,20 @@ unittests = provisiontests_env.Program('provisiontests', ['OCProvisioningTest.cp Alias("provisiontests", [unittests]) -env.AppendTarget('provisiontests') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': - out_dir = env.get('BUILD_DIR') - result_dir = env.get('BUILD_DIR') + '/test_out/' +provisiontests_env.AppendTarget('provisiontests') +if provisiontests_env.get('TEST') == '1': + if target_os in ['linux']: + out_dir = provisiontests_env.get('BUILD_DIR') + result_dir = os.path.join(provisiontests_env.get('BUILD_DIR'), 'test_out') + os.sep if not os.path.isdir(result_dir): os.makedirs(result_dir) provisiontests_env.AppendENVPath('GTEST_OUTPUT', ['xml:'+ result_dir]) provisiontests_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir]) - provisiontests_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs']) ut = provisiontests_env.Command ('ut', None, out_dir + 'resource/provisioning/unittests/provisiontests') AlwaysBuild ('ut') src_dir = provisiontests_env.get('SRC_DIR') svr_db_src_dir = src_dir + '/resource/provisioning/examples/' -svr_db_build_dir = env.get('BUILD_DIR') +'/resource/provisioning/unittests/' +svr_db_build_dir = os.path.join(provisiontests_env.get('BUILD_DIR'), 'resource', 'provisioning', 'unittests') provisiontests_env.Alias("install", provisiontests_env.Install( svr_db_build_dir, svr_db_src_dir + 'oic_svr_db_client.json')) diff --git a/resource/src/InProcClientWrapper.cpp b/resource/src/InProcClientWrapper.cpp index 32293f85d..fcc96c37d 100644 --- a/resource/src/InProcClientWrapper.cpp +++ b/resource/src/InProcClientWrapper.cpp @@ -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; @@ -190,7 +190,7 @@ namespace OC OCConnectivityType connectivityType, FindCallback& callback, QualityOfService QoS) { - if(!callback) + if (!callback) { return OC_STACK_INVALID_PARAM; } @@ -208,7 +208,7 @@ namespace OC ); auto cLock = m_csdkLock.lock(); - if(cLock) + if (cLock) { std::lock_guard<std::recursive_mutex> lock(*cLock); result = OCDoResource(nullptr, OC_REST_DISCOVER, @@ -255,7 +255,7 @@ namespace OC FindDeviceCallback& callback, QualityOfService QoS) { - if(!callback) + if (!callback) { return OC_STACK_INVALID_PARAM; } @@ -272,7 +272,7 @@ namespace OC ); auto cLock = m_csdkLock.lock(); - if(cLock) + if (cLock) { std::lock_guard<std::recursive_mutex> lock(*cLock); result = OCDoResource(nullptr, OC_REST_DISCOVER, @@ -293,7 +293,7 @@ namespace OC void parseServerHeaderOptions(OCClientResponse* clientResponse, HeaderOptions& serverHeaderOptions) { - if(clientResponse) + if (clientResponse) { // Parse header options from server uint16_t optionID; @@ -326,7 +326,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 @@ -350,7 +350,7 @@ namespace OC const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, GetCallback& callback, QualityOfService QoS) { - if(!callback) + if (!callback) { return OC_STACK_INVALID_PARAM; } @@ -367,7 +367,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]; @@ -403,7 +403,8 @@ namespace OC OCStackResult result = clientResponse->result; if (OC_STACK_OK == result || OC_STACK_RESOURCE_CREATED == result || - OC_STACK_RESOURCE_DELETED == result) + OC_STACK_RESOURCE_DELETED == result || + OC_STACK_RESOURCE_CHANGED == result) { parseServerHeaderOptions(clientResponse, serverHeaderOptions); try @@ -424,13 +425,13 @@ namespace OC std::string InProcClientWrapper::assembleSetResourceUri(std::string uri, const QueryParamsMap& queryParams) { - if(uri.back() == '/') + if (uri.back() == '/') { uri.resize(uri.size()-1); } ostringstream paramsList; - if(queryParams.size() > 0) + if (queryParams.size() > 0) { paramsList << '?'; } @@ -441,7 +442,7 @@ namespace OC } std::string queryString = paramsList.str(); - if(queryString.back() == ';') + if (queryString.back() == ';') { queryString.resize(queryString.size() - 1); } @@ -469,7 +470,7 @@ namespace OC const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, PostCallback& callback, QualityOfService QoS) { - if(!callback) + if (!callback) { return OC_STACK_INVALID_PARAM; } @@ -485,7 +486,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]; @@ -515,7 +516,7 @@ namespace OC const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, PutCallback& callback, QualityOfService QoS) { - if(!callback) + if (!callback) { return OC_STACK_INVALID_PARAM; } @@ -531,7 +532,7 @@ namespace OC auto cLock = m_csdkLock.lock(); - if(cLock) + if (cLock) { std::lock_guard<std::recursive_mutex> lock(*cLock); OCDoHandle handle; @@ -563,7 +564,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); } @@ -579,7 +580,7 @@ namespace OC DeleteCallback& callback, QualityOfService /*QoS*/) { - if(!callback) + if (!callback) { return OC_STACK_INVALID_PARAM; } @@ -594,7 +595,7 @@ namespace OC auto cLock = m_csdkLock.lock(); - if(cLock) + if (cLock) { OCHeaderOption options[MAX_HEADER_OPTIONS]; @@ -628,7 +629,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 @@ -643,10 +644,7 @@ namespace OC std::thread exec(context->callback, serverHeaderOptions, attrs, result, sequenceNumber); exec.detach(); - if(sequenceNumber == OC_OBSERVE_DEREGISTER) - { - return OC_STACK_DELETE_TRANSACTION; - } + return OC_STACK_KEEP_TRANSACTION; } @@ -656,7 +654,7 @@ namespace OC const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, ObserveCallback& callback, QualityOfService QoS) { - if(!callback) + if (!callback) { return OC_STACK_INVALID_PARAM; } @@ -688,7 +686,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]; @@ -721,7 +719,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]; @@ -763,7 +761,7 @@ namespace OC const std::string& host, const std::string& resourceType, OCConnectivityType connectivityType, SubscribeCallback& presenceHandler) { - if(!presenceHandler) + if (!presenceHandler) { return OC_STACK_INVALID_PARAM; } @@ -782,12 +780,12 @@ namespace OC 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; @@ -804,7 +802,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); @@ -828,7 +826,7 @@ namespace OC { int i = 0; - if( headerOptions.size() == 0) + if ( headerOptions.size() == 0) { return nullptr; } @@ -844,4 +842,144 @@ namespace OC 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; + } } diff --git a/resource/src/InProcServerWrapper.cpp b/resource/src/InProcServerWrapper.cpp index 522ef8278..82f01722b 100644 --- a/resource/src/InProcServerWrapper.cpp +++ b/resource/src/InProcServerWrapper.cpp @@ -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) diff --git a/resource/src/OCDirectPairing.cpp b/resource/src/OCDirectPairing.cpp new file mode 100644 index 000000000..4e50ac7c1 --- /dev/null +++ b/resource/src/OCDirectPairing.cpp @@ -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; + } +} diff --git a/resource/src/OCPlatform.cpp b/resource/src/OCPlatform.cpp index 4a7bc4956..42af9c1be 100644 --- a/resource/src/OCPlatform.cpp +++ b/resource/src/OCPlatform.cpp @@ -43,7 +43,7 @@ namespace OC } OCStackResult notifyAllObservers(OCResourceHandle resourceHandle, - QualityOfService QoS) + QualityOfService QoS) { return OCPlatform_impl::Instance().notifyAllObservers(resourceHandle, QoS); } @@ -54,106 +54,106 @@ 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 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); } @@ -174,42 +174,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) @@ -223,22 +222,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) @@ -250,6 +249,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 diff --git a/resource/src/OCPlatform_impl.cpp b/resource/src/OCPlatform_impl.cpp index 4abcb5a36..04939fdec 100644 --- a/resource/src/OCPlatform_impl.cpp +++ b/resource/src/OCPlatform_impl.cpp @@ -365,5 +365,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 diff --git a/resource/src/OCRepresentation.cpp b/resource/src/OCRepresentation.cpp index 47dce7161..79d7d3474 100644 --- a/resource/src/OCRepresentation.cpp +++ b/resource/src/OCRepresentation.cpp @@ -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) { @@ -744,6 +745,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(); @@ -764,7 +775,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; } diff --git a/resource/src/OCResource.cpp b/resource/src/OCResource.cpp index a3c8ec833..9ea55f669 100644 --- a/resource/src/OCResource.cpp +++ b/resource/src/OCResource.cpp @@ -122,7 +122,7 @@ 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) { diff --git a/resource/src/SConscript b/resource/src/SConscript index de1e678c2..d131b85ae 100644 --- a/resource/src/SConscript +++ b/resource/src/SConscript @@ -79,7 +79,8 @@ oclib_src = [ 'InProcServerWrapper.cpp', 'InProcClientWrapper.cpp', 'OCResourceRequest.cpp', - 'CAManager.cpp' + 'CAManager.cpp', + 'OCDirectPairing.cpp' ] oclib = oclib_env.SharedLibrary('oc', oclib_src) @@ -114,6 +115,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': diff --git a/resource/unit_tests.scons b/resource/unit_tests.scons index 08a9ffb30..74e2e8c8a 100644 --- a/resource/unit_tests.scons +++ b/resource/unit_tests.scons @@ -32,7 +32,7 @@ build_dir = env.get('BUILD_DIR') if target_os == 'linux': # Verify that 'google unit test' library is installed. If not, # get it and install it - SConscript(src_dir + '/extlibs/gtest/SConscript') + SConscript('#extlibs/gtest/SConscript') # Verify that 'hippomocks' mocking code is installed. If not, # get it and install it @@ -63,7 +63,7 @@ if target_os == 'linux': elif target_os == 'darwin': # Verify that 'google unit test' library is installed. If not, # get it and install it - SConscript(src_dir + '/extlibs/gtest/SConscript') + SConscript('#extlibs/gtest/SConscript') # Build C stack's unit tests. SConscript('csdk/stack/test/SConscript') diff --git a/resource/unittests/OCHeaderOptionTest.cpp b/resource/unittests/OCHeaderOptionTest.cpp index df1a5e356..fbe63b182 100644 --- a/resource/unittests/OCHeaderOptionTest.cpp +++ b/resource/unittests/OCHeaderOptionTest.cpp @@ -48,9 +48,15 @@ namespace OC { for(uint16_t i = 0; i < HeaderOption::MIN_HEADER_OPTIONID; ++i) { - ASSERT_THROW( - HeaderOption::OCHeaderOption(i,""), - OCException); + if (HeaderOption::IF_MATCH_OPTION_ID != i + && HeaderOption::IF_NONE_MATCH_OPTION_ID != i + && HeaderOption::LOCATION_PATH_OPTION_ID != i + && HeaderOption::LOCATION_QUERY_OPTION_ID != i) + { + ASSERT_THROW( + HeaderOption::OCHeaderOption(i,""), + OCException); + } } } diff --git a/resource/unittests/OCPlatformTest.cpp b/resource/unittests/OCPlatformTest.cpp index f2db5df55..d5aad2ea5 100644 --- a/resource/unittests/OCPlatformTest.cpp +++ b/resource/unittests/OCPlatformTest.cpp @@ -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)); + } } diff --git a/resource/unittests/OCRepresentationEncodingTest.cpp b/resource/unittests/OCRepresentationEncodingTest.cpp index a1ca1960f..4db6ea2d2 100644 --- a/resource/unittests/OCRepresentationEncodingTest.cpp +++ b/resource/unittests/OCRepresentationEncodingTest.cpp @@ -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); diff --git a/resource/unittests/OCResourceResponseTest.cpp b/resource/unittests/OCResourceResponseTest.cpp index 3b9e711f2..ca6a9f1e6 100644 --- a/resource/unittests/OCResourceResponseTest.cpp +++ b/resource/unittests/OCResourceResponseTest.cpp @@ -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/resource/unittests/SConscript b/resource/unittests/SConscript index bb02198bc..a2d2b4b71 100644 --- a/resource/unittests/SConscript +++ b/resource/unittests/SConscript @@ -18,12 +18,15 @@ # #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -Import('env') import os import os.path -unittests_env = env.Clone() +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +unittests_env = gtest_env.Clone() src_dir = unittests_env.get('SRC_DIR') +target_os = unittests_env.get('TARGET_OS') + ###################################################################### # Build flags ###################################################################### @@ -38,15 +41,14 @@ unittests_env.PrependUnique(CPPPATH = [ '../csdk/ocsocket/include', '../c_common/ocrandom/include', '../csdk/logger/include', - '#extlibs/gtest/gtest-1.7.0/include', '#extlibs/hippomocks-master/HippoMocks', '#extlibs/hippomocks-master/HippoMocksTest' ]) -unittests_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) -unittests_env.AppendUnique(LIBS = ['-lpthread']) -unittests_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) -unittests_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs']) +if target_os not in ['windows']: + unittests_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) + unittests_env.AppendUnique(LIBS = ['pthread']) +unittests_env.AppendUnique(LIBPATH = [unittests_env.get('BUILD_DIR')]) unittests_env.PrependUnique(LIBS = [ 'oc', 'octbstack', @@ -57,10 +59,10 @@ unittests_env.PrependUnique(LIBS = [ 'gtest_main' ]) -if env.get('SECURED') == '1': +if unittests_env.get('SECURED') == '1': unittests_env.AppendUnique(LIBS = ['tinydtls']) -if env.get('LOGGING'): +if unittests_env.get('LOGGING'): unittests_env.AppendUnique(CPPDEFINES = ['TB_LOG']) ###################################################################### @@ -77,10 +79,9 @@ unittests = unittests_env.Program('unittests', ['ConstructResourceTest.cpp', Alias("unittests", [unittests]) -env.AppendTarget('unittests') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': +unittests_env.AppendTarget('unittests') +if unittests_env.get('TEST') == '1': + if target_os in ['linux']: from tools.scons.RunTest import * run_test(unittests_env, 'resource_unittests_unittests.memcheck', @@ -88,7 +89,7 @@ if env.get('TEST') == '1': src_dir = unittests_env.get('SRC_DIR') svr_db_src_dir = os.path.join(src_dir, 'resource/examples/') -svr_db_build_dir = os.path.join(env.get('BUILD_DIR'), 'resource/unittests/') +svr_db_build_dir = os.path.join(unittests_env.get('BUILD_DIR'), 'resource', 'unittests') + os.sep unittests_env.Alias("install", unittests_env.Install(svr_db_build_dir, os.path.join(svr_db_src_dir, diff --git a/service/easy-setup/enrollee/unittests/SConscript b/service/easy-setup/enrollee/unittests/SConscript index 6dc60e1ba..ad6c45892 100644 --- a/service/easy-setup/enrollee/unittests/SConscript +++ b/service/easy-setup/enrollee/unittests/SConscript @@ -17,11 +17,12 @@ # #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -Import('env') import os import os.path -enrollee_test_env = env.Clone() +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +enrollee_test_env = gtest_env.Clone() src_dir = enrollee_test_env.get('SRC_DIR') ###################################################################### @@ -29,7 +30,6 @@ src_dir = enrollee_test_env.get('SRC_DIR') ###################################################################### enrollee_test_env.PrependUnique(CPPPATH = [ - enrollee_test_env.get('SRC_DIR') + '/extlibs/gtest/gtest-1.7.0/include', enrollee_test_env.get('SRC_DIR') + '/resource/c_common/ocrandom/include', enrollee_test_env.get('SRC_DIR') + '/resource/csdk/stack/include/internal', enrollee_test_env.get('SRC_DIR') + '/resource/csdk/connectivity/api', @@ -49,9 +49,8 @@ enrollee_test_env.PrependUnique(CPPPATH = [ enrollee_test_env.get('SRC_DIR') + '/service/easy-setup/enrollee/src']) enrollee_test_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) -enrollee_test_env.AppendUnique(LIBS = ['-lpthread']) -enrollee_test_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) -enrollee_test_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs']) +enrollee_test_env.AppendUnique(LIBS = ['pthread']) +enrollee_test_env.AppendUnique(LIBPATH = [enrollee_test_env.get('BUILD_DIR')]) enrollee_test_env.PrependUnique(LIBS = ['m', 'octbstack', 'ocsrm', @@ -60,17 +59,17 @@ enrollee_test_env.PrependUnique(LIBS = ['m', 'gtest', 'gtest_main']) -target_os = env.get('TARGET_OS') +target_os = enrollee_test_env.get('TARGET_OS') if target_os != 'darwin': enrollee_test_env.PrependUnique(LIBS = ['oc_logger']) -if env.get('SECURED') == '1': +if enrollee_test_env.get('SECURED') == '1': enrollee_test_env.AppendUnique(LIBS = ['tinydtls']) -if env.get('LOGGING'): +if enrollee_test_env.get('LOGGING'): enrollee_test_env.AppendUnique(CPPDEFINES = ['TB_LOG']) -if env.get('ES_SOFTAP_MODE') == 'ENROLLEE_SOFTAP': +if enrollee_test_env.get('ES_SOFTAP_MODE') == 'ENROLLEE_SOFTAP': print "ES_SOFTAP_MODE == ENROLLEE_SOFTAP" enrollee_test_env.AppendUnique(CPPDEFINES = ['ENROLLEE_SOFTAP']) @@ -83,9 +82,9 @@ enrolleetests = enrollee_test_env.Program('enrolleetests', ['enrolleetests.cpp'] Alias("test", [enrolleetests]) -env.AppendTarget('test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') +enrolleetests.AppendTarget('test') +if enrollee_test_env.get('TEST') == '1': + target_os = enrollee_test_env.get('TARGET_OS') if target_os == 'linux': from tools.scons.RunTest import * run_test(enrollee_test_env, diff --git a/service/easy-setup/mediator/csdk/SConscript b/service/easy-setup/mediator/csdk/SConscript index 675ab6ba5..fea497383 100644 --- a/service/easy-setup/mediator/csdk/SConscript +++ b/service/easy-setup/mediator/csdk/SConscript @@ -75,7 +75,12 @@ if target_os == 'linux': easy_setup_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) easy_setup_env.AppendUnique(RPATH = [env.get('BUILD_DIR')]) easy_setup_env.AppendUnique(CXXFLAGS = ['-pthread']) - easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction']) + easy_setup_env.PrependUnique(LIBS = ['coap']) + easy_setup_env.AppendUnique(LIBS = ['connectivity_abstraction']) + easy_setup_env.AppendUnique(LIBS = ['oc_logger']) + easy_setup_env.AppendUnique(LIBS = ['octbstack']) + easy_setup_env.AppendUnique(LIBS = ['oc']) + easy_setup_env.AppendUnique(LIBS = ['pthread']) ###################################################################### # Android Mediator @@ -84,7 +89,13 @@ if target_os == 'android': easy_setup_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) easy_setup_env.AppendUnique(RPATH = [env.get('BUILD_DIR')]) easy_setup_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions']) - easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'gnustl_shared']) + easy_setup_env.PrependUnique(LIBS = ['coap']) + easy_setup_env.AppendUnique(LIBS = ['connectivity_abstraction']) + easy_setup_env.AppendUnique(LIBS = ['oc_logger']) + easy_setup_env.AppendUnique(LIBS = ['octbstack']) + easy_setup_env.AppendUnique(LIBS = ['oc']) + easy_setup_env.AppendUnique(LIBS = ['gnustl_shared']) + if not env.get('RELEASE'): easy_setup_env.AppendUnique(LIBS = ['log']) diff --git a/service/easy-setup/mediator/csdk/src/provisioning.cpp b/service/easy-setup/mediator/csdk/src/provisioning.cpp index ac6ac5bc6..00d89cf5f 100755 --- a/service/easy-setup/mediator/csdk/src/provisioning.cpp +++ b/service/easy-setup/mediator/csdk/src/provisioning.cpp @@ -43,7 +43,7 @@ bool gProvisioningCondFlag = false; static ProvConfig *gProvConfig; static WiFiOnboadingConnection *gOnboardConn; -static char gSzFindResourceQueryUri[64] = +static char gSzFindResourceQueryUri[MAX_QUERY_LENGTH] = { 0 }; /** diff --git a/service/easy-setup/mediator/csdk/src/provisioningapi.cpp b/service/easy-setup/mediator/csdk/src/provisioningapi.cpp index 988921e8b..42acd8360 100755 --- a/service/easy-setup/mediator/csdk/src/provisioningapi.cpp +++ b/service/easy-setup/mediator/csdk/src/provisioningapi.cpp @@ -97,7 +97,7 @@ void UnRegisterCallback() OCStackResult StartProvisioning(const ProvConfig *provConfig, WiFiOnboadingConnection *onboardConn) { - char findQuery[64] = + char findQuery[MAX_QUERY_LENGTH] = { 0 }; if (provConfig == NULL || onboardConn == NULL) diff --git a/service/easy-setup/mediator/csdk/src/wifiprovisioning.cpp b/service/easy-setup/mediator/csdk/src/wifiprovisioning.cpp index d8d40feaa..08ecc2056 100755 --- a/service/easy-setup/mediator/csdk/src/wifiprovisioning.cpp +++ b/service/easy-setup/mediator/csdk/src/wifiprovisioning.cpp @@ -219,7 +219,7 @@ OCStackApplicationResult FindProvisioningResourceResponse(void* /*ctx*/, OCDoHan return OC_STACK_DELETE_TRANSACTION; } - char szQueryUri[64] = + char szQueryUri[MAX_QUERY_LENGTH] = { 0 }; OCDiscoveryPayload *discoveryPayload = (OCDiscoveryPayload *) (clientResponse->payload); diff --git a/service/easy-setup/mediator/csdk/unittests/SConscript b/service/easy-setup/mediator/csdk/unittests/SConscript index 734f05172..f7c0ff12c 100644 --- a/service/easy-setup/mediator/csdk/unittests/SConscript +++ b/service/easy-setup/mediator/csdk/unittests/SConscript @@ -22,30 +22,28 @@ # Mediator[CSDK] Unit Test build script ## import os -Import('env') -if env.get('RELEASE'): - env.AppendUnique(CCFLAGS = ['-Os']) - env.AppendUnique(CPPDEFINES = ['NDEBUG']) +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +lib_env = gtest_env.Clone() + +if lib_env.get('RELEASE'): + lib_env.AppendUnique(CCFLAGS = ['-Os']) + lib_env.AppendUnique(CPPDEFINES = ['NDEBUG']) else: - env.AppendUnique(CCFLAGS = ['-g']) + lib_env.AppendUnique(CCFLAGS = ['-g']) -if env.get('LOGGING'): - env.AppendUnique(CPPDEFINES = ['TB_LOG']) +if lib_env.get('LOGGING'): + lib_env.AppendUnique(CPPDEFINES = ['TB_LOG']) # Add third party libraries -lib_env = env.Clone() -SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') - -target_os = env.get('TARGET_OS') -if target_os == 'linux': - # Verify that 'google unit test' library is installed. If not, - # get it and install it - SConscript(env.get('SRC_DIR') + '/extlibs/gtest/SConscript') +SConscript('#service/third_party_libs.scons', 'lib_env') +target_os = lib_env.get('TARGET_OS') +if target_os in ['linux']: # Verify that 'hippomocks' mocking code is installed. If not, # get it and install it - SConscript(env.get('SRC_DIR') + '/extlibs/hippomocks.scons') + SConscript('#extlibs/hippomocks.scons') mediator_csdk_test_env = lib_env.Clone() @@ -53,27 +51,24 @@ mediator_csdk_test_env = lib_env.Clone() #unit test setting ###################################################################### src_dir = lib_env.get('SRC_DIR') -gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0' ###################################################################### # Build flags ###################################################################### -gtest = File(gtest_dir + '/lib/.libs/libgtest.a') -gtest_main = File(gtest_dir + '/lib/.libs/libgtest_main.a') mediator_csdk_test_env.AppendUnique( CPPPATH = [ src_dir + '/extlibs/hippomocks-master', - src_dir + '/extlibs/gtest/gtest-1.7.0/include', '../inc', '../../../inc', ]) -if target_os not in ['windows', 'winrt']: - mediator_csdk_test_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall']) - if target_os != 'android': - mediator_csdk_test_env.AppendUnique(CXXFLAGS = ['-pthread']) - mediator_csdk_test_env.AppendUnique(LIBS = ['pthread']) +if target_os not in ['windows']: + mediator_csdk_test_env.AppendUnique(LIBS = ['dl']) + mediator_csdk_test_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall']) + if target_os != 'android': + mediator_csdk_test_env.AppendUnique(CXXFLAGS = ['-pthread']) + mediator_csdk_test_env.AppendUnique(LIBS = ['pthread']) mediator_csdk_test_env.PrependUnique(LIBS = [ 'ESMediatorCSDK', @@ -82,22 +77,20 @@ mediator_csdk_test_env.PrependUnique(LIBS = [ 'oc_logger', 'oc_logger_core', 'connectivity_abstraction', - gtest, - gtest_main]) - -mediator_csdk_test_env.AppendUnique(LIBS = ['dl']) + 'gtest', + 'gtest_main']) ###################################################################### # Build Test ###################################################################### -mediator_csdk_test_src = env.Glob('./*.cpp') +mediator_csdk_test_src = mediator_csdk_test_env.Glob('./*.cpp') mediator_csdk_test = mediator_csdk_test_env.Program('mediator_csdk_test', mediator_csdk_test_src) Alias("mediator_csdk_test", mediator_csdk_test) -env.AppendTarget('mediator_csdk_test') +mediator_csdk_test_env.AppendTarget('mediator_csdk_test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': +if mediator_csdk_test_env.get('TEST') == '1': + target_os = mediator_csdk_test_env.get('TARGET_OS') + if target_os in ['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') diff --git a/service/easy-setup/mediator/richsdk/SConscript b/service/easy-setup/mediator/richsdk/SConscript index f63176157..54c187583 100644 --- a/service/easy-setup/mediator/richsdk/SConscript +++ b/service/easy-setup/mediator/richsdk/SConscript @@ -71,7 +71,12 @@ if target_os in ['android']: easy_setup_env.AppendUnique(LIBPATH = [env.get('SRC_DIR')+'/android/android_api/base/libs/armeabi']) easy_setup_env.AppendUnique(RPATH = [env.get('BUILD_DIR')]) easy_setup_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions']) - easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'gnustl_shared']) + easy_setup_env.PrependUnique(LIBS = ['coap']) + easy_setup_env.AppendUnique(LIBS = ['connectivity_abstraction']) + easy_setup_env.AppendUnique(LIBS = ['oc_logger']) + easy_setup_env.AppendUnique(LIBS = ['octbstack']) + easy_setup_env.AppendUnique(LIBS = ['oc']) + easy_setup_env.AppendUnique(LIBS = ['gnustl_shared']) if env.get('SECURED') == '1': easy_setup_env.AppendUnique(LIBS = ['ocpmapi','ocprovision']) if not env.get('RELEASE'): @@ -81,7 +86,12 @@ if target_os in ['linux']: easy_setup_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) easy_setup_env.AppendUnique(RPATH = [env.get('BUILD_DIR')]) easy_setup_env.AppendUnique(CXXFLAGS = ['-pthread']) - easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction']) + easy_setup_env.PrependUnique(LIBS = ['coap']) + easy_setup_env.AppendUnique(LIBS = ['connectivity_abstraction']) + easy_setup_env.AppendUnique(LIBS = ['oc_logger']) + easy_setup_env.AppendUnique(LIBS = ['octbstack']) + easy_setup_env.AppendUnique(LIBS = ['oc']) + easy_setup_env.AppendUnique(LIBS = ['pthread']) if env.get('SECURED') == '1': easy_setup_env.AppendUnique(LIBS = ['ocpmapi', 'ocprovision']) diff --git a/service/easy-setup/mediator/richsdk/unittests/SConscript b/service/easy-setup/mediator/richsdk/unittests/SConscript index 480df1992..6d4a08df4 100644 --- a/service/easy-setup/mediator/richsdk/unittests/SConscript +++ b/service/easy-setup/mediator/richsdk/unittests/SConscript @@ -18,34 +18,32 @@ # #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +import os + +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +lib_env = gtest_env.Clone() + ## # Mediator[RichSDK] Unit Test build script ## -import os -Import('env') - -if env.get('RELEASE'): - env.AppendUnique(CCFLAGS = ['-Os']) - env.AppendUnique(CPPDEFINES = ['NDEBUG']) +if lib_env.get('RELEASE'): + lib_env.AppendUnique(CCFLAGS = ['-Os']) + lib_env.AppendUnique(CPPDEFINES = ['NDEBUG']) else: - env.AppendUnique(CCFLAGS = ['-g']) + lib_env.AppendUnique(CCFLAGS = ['-g']) -if env.get('LOGGING'): - env.AppendUnique(CPPDEFINES = ['TB_LOG']) +if lib_env.get('LOGGING'): + lib_env.AppendUnique(CPPDEFINES = ['TB_LOG']) # Add third party libraries -lib_env = env.Clone() -SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') +SConscript(lib_env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') -target_os = env.get('TARGET_OS') +target_os = lib_env.get('TARGET_OS') if target_os == 'linux': - # Verify that 'google unit test' library is installed. If not, - # get it and install it - SConscript(env.get('SRC_DIR') + '/extlibs/gtest/SConscript') - # Verify that 'hippomocks' mocking code is installed. If not, # get it and install it - SConscript(env.get('SRC_DIR') + '/extlibs/hippomocks.scons') + SConscript(lib_env.get('SRC_DIR') + '/extlibs/hippomocks.scons') mediator_rich_test_env = lib_env.Clone() @@ -53,18 +51,14 @@ mediator_rich_test_env = lib_env.Clone() #unit test setting ###################################################################### src_dir = lib_env.get('SRC_DIR') -gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0' ###################################################################### # Build flags ###################################################################### -gtest = File(gtest_dir + '/lib/.libs/libgtest.a') -gtest_main = File(gtest_dir + '/lib/.libs/libgtest_main.a') mediator_rich_test_env.AppendUnique( CPPPATH = [ src_dir + '/extlibs/hippomocks-master', - src_dir + '/extlibs/gtest/gtest-1.7.0/include', '../inc', '../../../inc', ]) @@ -76,33 +70,32 @@ if target_os not in ['windows', 'winrt']: mediator_rich_test_env.AppendUnique(LIBS = ['pthread']) -if env.get('SECURED') == '1': +if mediator_rich_test_env.get('SECURED') == '1': mediator_rich_test_env.PrependUnique(LIBS = ['tinydtls','ocprovision', 'ocpmapi']) mediator_rich_test_env.PrependUnique(LIBS = [ - 'oc', - 'octbstack', + 'coap', + 'connectivity_abstraction', 'oc_logger', 'oc_logger_core', - 'connectivity_abstraction', - 'coap', + 'octbstack', + 'oc', 'ESMediatorRich', - gtest, - gtest_main]) + 'gtest', + 'gtest_main']) mediator_rich_test_env.AppendUnique(LIBS = ['dl']) ###################################################################### # Build Test ###################################################################### -mediator_richsdk_test_src = env.Glob('./*.cpp') +mediator_richsdk_test_src = mediator_rich_test_env.Glob('./*.cpp') mediator_richsdk_test = mediator_rich_test_env.Program('mediator_richsdk_test', mediator_richsdk_test_src) Alias("mediator_richsdk_test", mediator_richsdk_test) -env.AppendTarget('mediator_richsdk_test') +mediator_rich_test_env.AppendTarget('mediator_richsdk_test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') +if mediator_rich_test_env.get('TEST') == '1': if target_os == 'linux': from tools.scons.RunTest import * - run_test(mediator_rich_test_env, '', 'service/easy-setup/mediator/richsdk/unittests/mediator_richsdk_test')
\ No newline at end of file + run_test(mediator_rich_test_env, '', 'service/easy-setup/mediator/richsdk/unittests/mediator_richsdk_test') diff --git a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/packaging/com.oic.es.sample.spec b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/packaging/com.oic.es.sample.spec index 3b49c9a5e..500b64ddf 100644 --- a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/packaging/com.oic.es.sample.spec +++ b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/packaging/com.oic.es.sample.spec @@ -1,9 +1,10 @@ %define PREFIX /usr/apps/com.oic.es.sample %define ROOTDIR %{_builddir}/%{name}-%{version} +%{!?VERBOSE: %define VERBOSE 1} 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 @@ -31,7 +32,7 @@ EasySetup Sample application %build -scons TARGET_OS=tizen LOGGING=True TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} ROUTING=%{ROUTING} ES_ROLE=%{ES_ROLE} ES_TARGET_ENROLLEE=%{ES_TARGET_ENROLLEE} ES_SOFTAP_MODE=%{ES_SOFTAP_MODE} +scons VERBOSE=%{VERBOSE} TARGET_OS=tizen LOGGING=True TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} ROUTING=%{ROUTING} ES_ROLE=%{ES_ROLE} ES_TARGET_ENROLLEE=%{ES_TARGET_ENROLLEE} ES_SOFTAP_MODE=%{ES_SOFTAP_MODE} %install diff --git a/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.dat b/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.dat Binary files differindex cb6a70f0f..3884c30bf 100644 --- a/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.dat +++ b/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.dat diff --git a/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.json b/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.json index 592bc1bf9..6878fd974 100644 --- a/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.json +++ b/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.json @@ -1,88 +1,88 @@ -{
- "acl": {
- "aclist": {
- "aces": [
- {
- "subjectuuid": "*",
- "resources": [
- {
- "href": "/oic/res",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/d",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "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": ""
- }
- ],
- "permission": 2
- },
- {
- "subjectuuid": "*",
- "resources": [
- {
- "href": "/oic/sec/doxm",
- "rel": "",
- "rt": "",
- "if": ""
- } ,
- {
- "href": "/oic/sec/pstat",
- "rel": "",
- "rt": "",
- "if": ""
- }
- ],
- "permission": 2
- }
- ]
- },
- "rowneruuid" : "61646d69-6e44-6576-6963-655575696430"
- },
- "pstat": {
- "isop": true,
- "deviceuuid": "61646d69-6e44-6576-6963-655575696430",
- "rowneruuid": "61646d69-6e44-6576-6963-655575696430",
- "cm": 0,
- "tm": 0,
- "om": 3,
- "sm": 3
- },
- "doxm": {
- "oxms": [0],
- "oxmsel": 0,
- "sct": 1,
- "owned": true,
- "deviceuuid": "61646d69-6e44-6576-6963-655575696430",
- "devowneruuid": "61646d69-6e44-6576-6963-655575696430",
- "rowneruuid": "61646d69-6e44-6576-6963-655575696430",
- "dpc": false
- }
-}
+{ + "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"] + }, + { + "href": "/oic/ad", + "rel": "", + "rt": ["oic.wk.ad"], + "if": ["oic.if.baseline"] + }, + { + "href": "/oic/sec/acl", + "rel": "", + "rt": ["oic.r.acl"], + "if": ["oic.if.baseline"] + }, + { + "href": "/oic/res/types/d", + "rel": "", + "rt": ["oic.wk.res"], + "if": ["oic.if.baseline"] + } + ], + "permission": 2 + }, + { + "subjectuuid": "*", + "resources": [ + { + "href": "/oic/sec/doxm", + "rel": "", + "rt": ["oic.r.doxm"], + "if": ["oic.if.baseline"] + }, + { + "href": "/oic/sec/pstat", + "rel": "", + "rt": ["oic.r.pstat"], + "if": ["oic.if.baseline"] + } + ], + "permission": 2 + } + ] + }, + "rowneruuid" : "61646d69-6e44-6576-6963-655575696430" + }, + "pstat": { + "isop": true, + "deviceuuid": "61646d69-6e44-6576-6963-655575696430", + "rowneruuid": "61646d69-6e44-6576-6963-655575696430", + "cm": 0, + "tm": 0, + "om": 3, + "sm": 3 + }, + "doxm": { + "oxms": [0], + "oxmsel": 0, + "sct": 1, + "owned": true, + "deviceuuid": "61646d69-6e44-6576-6963-655575696430", + "devowneruuid": "61646d69-6e44-6576-6963-655575696430", + "rowneruuid": "61646d69-6e44-6576-6963-655575696430", + "x.org.iotivity.dpc": false + } +} diff --git a/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/SConscript b/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/SConscript index ef24ed2b1..a792b7a6f 100644 --- a/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/SConscript +++ b/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/SConscript @@ -58,7 +58,14 @@ mediator_env.PrependUnique(CPPPATH = [ env.get('SRC_DIR') + '/service/easy-setup/mediator/richsdk/src', env.get('SRC_DIR') + '/service/easy-setup/inc']) -mediator_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction', 'coap', 'ESMediatorRich']) +mediator_env.PrependUnique(LIBS = ['coap']) +mediator_env.AppendUnique(LIBS = ['connectivity_abstraction']) +mediator_env.AppendUnique(LIBS = ['oc_logger']) +mediator_env.AppendUnique(LIBS = ['octbstack']) +mediator_env.AppendUnique(LIBS = ['oc']) +mediator_env.AppendUnique(LIBS = ['pthread']) +mediator_env.AppendUnique(LIBS = ['ESMediatorRich']) + if env.get('SECURED') == '1': mediator_env.PrependUnique(LIBS = ['ocpmapi', 'ocprovision']) diff --git a/service/resource-container/SConscript b/service/resource-container/SConscript index 9a27b96c1..62be9f2b5 100644 --- a/service/resource-container/SConscript +++ b/service/resource-container/SConscript @@ -100,9 +100,18 @@ try: except KeyError: print '' - -resource_container_env.PrependUnique(LIBS = ['rcs_client', 'rcs_server', 'rcs_common', 'oc','octbstack', 'oc_logger', 'connectivity_abstraction']) -resource_container_env.AppendUnique(LIBS = ['dl', 'boost_system', 'boost_date_time', 'boost_thread']) +resource_container_env.PrependUnique(LIBS = ['coap']) +resource_container_env.AppendUnique(LIBS = ['connectivity_abstraction']) +resource_container_env.AppendUnique(LIBS = ['oc_logger']) +resource_container_env.AppendUnique(LIBS = ['octbstack']) +resource_container_env.AppendUnique(LIBS = ['oc']) +resource_container_env.AppendUnique(LIBS = ['rcs_client']) +resource_container_env.AppendUnique(LIBS = ['rcs_server']) +resource_container_env.AppendUnique(LIBS = ['rcs_common']) +resource_container_env.AppendUnique(LIBS = ['dl']) +resource_container_env.AppendUnique(LIBS = ['boost_system']) +resource_container_env.AppendUnique(LIBS = ['boost_date_time']) +resource_container_env.AppendUnique(LIBS = ['boost_thread']) if int(containerJavaSupport): try: @@ -244,4 +253,4 @@ env.AppendTarget('containersampleclient') # Build Container Java SDK ###################################################################### if target_os == 'android': - SConscript('android/SConscript')
\ No newline at end of file + SConscript('android/SConscript') diff --git a/service/resource-container/examples/BMISensorBundle/src/BMISensor.cpp b/service/resource-container/examples/BMISensorBundle/src/BMISensor.cpp index f56bc07d7..6bf73e17a 100644 --- a/service/resource-container/examples/BMISensorBundle/src/BMISensor.cpp +++ b/service/resource-container/examples/BMISensorBundle/src/BMISensor.cpp @@ -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) diff --git a/service/resource-container/examples/BMISensorBundle/src/inputSensors/HeightSensorApp/SConscript b/service/resource-container/examples/BMISensorBundle/src/inputSensors/HeightSensorApp/SConscript index 22bd8216f..20516e4be 100644 --- a/service/resource-container/examples/BMISensorBundle/src/inputSensors/HeightSensorApp/SConscript +++ b/service/resource-container/examples/BMISensorBundle/src/inputSensors/HeightSensorApp/SConscript @@ -16,11 +16,11 @@ 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 = ['oc']) -linux_sample_env.AppendUnique(LIBS = ['octbstack']) -linux_sample_env.AppendUnique(LIBS = ['libconnectivity_abstraction']) 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 = ['octbstack']) +linux_sample_env.AppendUnique(LIBS = ['oc']) linux_sample_env.AppendUnique(LIBS = ['pthread']) if env.get('SECURED') == '1': @@ -36,4 +36,4 @@ if 'rt' in linux_sample_env.get('LIBS'): ###################################################################### heightsensorapp = linux_sample_env.Program('HeightSensorApp', 'src/HeightSensorApp.cpp') Alias("heightsensorapp_sample", heightsensorapp) -env.AppendTarget('heightsensorapp')
\ No newline at end of file +env.AppendTarget('heightsensorapp') diff --git a/service/resource-container/examples/BMISensorBundle/src/inputSensors/WeightSensorApp/SConscript b/service/resource-container/examples/BMISensorBundle/src/inputSensors/WeightSensorApp/SConscript index 31df5caca..6b7ab830b 100644 --- a/service/resource-container/examples/BMISensorBundle/src/inputSensors/WeightSensorApp/SConscript +++ b/service/resource-container/examples/BMISensorBundle/src/inputSensors/WeightSensorApp/SConscript @@ -16,11 +16,11 @@ 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 = ['oc']) +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 = ['libconnectivity_abstraction']) -linux_sample_env.AppendUnique(LIBS = ['libcoap']) -linux_sample_env.AppendUnique(LIBS = ['liboc_logger']) +linux_sample_env.AppendUnique(LIBS = ['oc']) linux_sample_env.AppendUnique(LIBS = ['pthread']) if env.get('SECURED') == '1': @@ -36,4 +36,4 @@ if 'rt' in linux_sample_env.get('LIBS'): ###################################################################### weightsensorapp = linux_sample_env.Program('WeightSensorApp', 'src/WeightSensorApp.cpp') Alias("weightsensorapp_sample", weightsensorapp) -env.AppendTarget('weightsensorapp')
\ No newline at end of file +env.AppendTarget('weightsensorapp') diff --git a/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp/SConscript b/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp/SConscript index 9b065edea..ee61a9a6f 100644 --- a/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp/SConscript +++ b/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp/SConscript @@ -16,11 +16,11 @@ linux_sample_env.AppendUnique(CPPPATH = ['include']) linux_sample_env.AppendUnique(CXXFLAGS = ['-Wall', '-pthread','-std=c++0x']) linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX']) linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) -linux_sample_env.AppendUnique(LIBS = ['oc']) +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 = ['libconnectivity_abstraction']) -linux_sample_env.AppendUnique(LIBS = ['libcoap']) -linux_sample_env.AppendUnique(LIBS = ['liboc_logger']) +linux_sample_env.AppendUnique(LIBS = ['oc']) linux_sample_env.AppendUnique(LIBS = ['pthread']) if env.get('SECURED') == '1': diff --git a/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp1/SConscript b/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp1/SConscript index 31097933e..7fa770c72 100644 --- a/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp1/SConscript +++ b/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp1/SConscript @@ -16,11 +16,11 @@ linux_sample_env.AppendUnique(CPPPATH = ['include']) linux_sample_env.AppendUnique(CXXFLAGS = ['-Wall', '-pthread','-std=c++0x']) linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX']) linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) -linux_sample_env.AppendUnique(LIBS = ['oc']) +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 = ['libconnectivity_abstraction']) -linux_sample_env.AppendUnique(LIBS = ['libcoap']) -linux_sample_env.AppendUnique(LIBS = ['liboc_logger']) +linux_sample_env.AppendUnique(LIBS = ['oc']) linux_sample_env.AppendUnique(LIBS = ['pthread']) if env.get('SECURED') == '1': diff --git a/service/resource-container/src/BundleInfoInternal.cpp b/service/resource-container/src/BundleInfoInternal.cpp index a15ae9cdd..893db0089 100644 --- a/service/resource-container/src/BundleInfoInternal.cpp +++ b/service/resource-container/src/BundleInfoInternal.cpp @@ -32,8 +32,8 @@ namespace OIC m_resourceCreator = nullptr; m_resourceDestroyer = nullptr; m_bundleHandle = nullptr; - m_so_bundle = nullptr; + m_so_bundle = false; m_loaded = false; m_activated = false; m_java_bundle = false; diff --git a/service/resource-container/unittests/SConscript b/service/resource-container/unittests/SConscript index ecc530645..b57c30c9f 100644 --- a/service/resource-container/unittests/SConscript +++ b/service/resource-container/unittests/SConscript @@ -22,35 +22,38 @@ # ResourceContainer (rcs_container) Unit Test build script ## import os -Import('env') - import os.path +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +lib_env = gtest_env.Clone() +target_os = lib_env.get('TARGET_OS') +src_dir = lib_env.get('SRC_DIR') + containerJavaSupport = ARGUMENTS.get('containerJavaSupport',0) def filtered_glob(env, pattern, omit=[], ondisk=True, source=False, strings=False): return filter( lambda f: os.path.basename(f.path) not in omit, - env.Glob(pattern)) + lib_env.Glob(pattern)) -env.AddMethod(filtered_glob, "FilteredGlob"); +lib_env.AddMethod(filtered_glob, "FilteredGlob"); -if env.get('RELEASE'): - env.AppendUnique(CCFLAGS = ['-Os']) - env.AppendUnique(CPPDEFINES = ['NDEBUG']) +if lib_env.get('RELEASE'): + lib_env.AppendUnique(CCFLAGS = ['-Os']) + lib_env.AppendUnique(CPPDEFINES = ['NDEBUG']) else: - env.AppendUnique(CCFLAGS = ['-g']) + lib_env.AppendUnique(CCFLAGS = ['-g']) -if env.get('LOGGING'): - env.AppendUnique(CPPDEFINES = ['TB_LOG']) +if lib_env.get('LOGGING'): + lib_env.AppendUnique(CPPDEFINES = ['TB_LOG']) # Add third party libraries -lib_env = env.Clone() -SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') +SConscript(src_dir + '/service/third_party_libs.scons', 'lib_env') container_gtest_env = lib_env.Clone() @@ -72,23 +75,17 @@ if int(containerJavaSupport): container_gtest_env.Append(CPPDEFINES={'JAVA_SUPPORT_TEST':0}) -target_os = env.get('TARGET_OS') ######################### unit test setting ########################## -src_dir = lib_env.get('SRC_DIR') -gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0' ###################################################################### ###################################################################### # Build flags ###################################################################### -gtest = File(gtest_dir + '/lib/.libs/libgtest.a') -gtest_main = File(gtest_dir + '/lib/.libs/libgtest_main.a') - container_gtest_env.AppendUnique( CPPPATH = [ - env.get('SRC_DIR')+'/extlibs', + src_dir + '/extlibs', '../include', '../../resource-encapsulation/include', '../../resource-encapsulation/src/common/utils/include', @@ -107,17 +104,18 @@ if int(containerJavaSupport): print '' if target_os not in ['windows', 'winrt']: + container_gtest_env.AppendUnique(LIBS = ['dl']) container_gtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall']) + container_gtest_env.AppendUnique(CCFLAGS = ['-Wnoexcept']) if target_os != 'android': container_gtest_env.AppendUnique(CXXFLAGS = ['-pthread']) container_gtest_env.AppendUnique(LIBS = ['pthread']) -if target_os == 'android': +if target_os in ['android']: container_gtest_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions']) container_gtest_env.PrependUnique(LIBS = ['gnustl_shared', 'compatibility', 'log']) -container_gtest_env.PrependUnique(CPPPATH = [env.get('SRC_DIR')+'/extlibs/hippomocks-master', - gtest_dir + '/include']) +container_gtest_env.PrependUnique(CPPPATH = [src_dir + '/extlibs/hippomocks-master']) if int(containerJavaSupport): try: @@ -125,11 +123,7 @@ if int(containerJavaSupport): except KeyError: print '' -container_gtest_env.AppendUnique(CCFLAGS = ['-Wnoexcept']) - -container_gtest_env.PrependUnique(LIBS = ['rcs_container', 'rcs_client', 'rcs_server', 'rcs_common', 'oc','octbstack', 'oc_logger', 'oc_logger_core', 'connectivity_abstraction', gtest, gtest_main]) - -container_gtest_env.AppendUnique(LIBS = ['dl']) +container_gtest_env.PrependUnique(LIBS = ['rcs_container', 'rcs_client', 'rcs_server', 'rcs_common', 'oc','octbstack', 'oc_logger', 'oc_logger_core', 'connectivity_abstraction', 'gtest', 'gtest_main']) if int(containerJavaSupport): try: @@ -161,11 +155,11 @@ test_bundle_env.InstallTarget(TestBundle, 'libTestBundle') ###################################################################### # Build Test ###################################################################### -container_gtest_src = env.Glob('./*.cpp') +container_gtest_src = container_gtest_env.Glob('./*.cpp') container_test = container_gtest_env.Program('container_test', container_gtest_src) Alias("container_test", container_test) -env.AppendTarget('container_test') +container_gtest_env.AppendTarget('container_test') # Copy test configuration Command("./ResourceContainerTestConfig.xml","./ResourceContainerTestConfig.xml", Copy("$TARGET", "$SOURCE")) @@ -175,10 +169,9 @@ Ignore("./ResourceContainerInvalidConfig.xml", "./ResourceContainerInvalidConfig Command("./TestBundleJava/hue-0.1-jar-with-dependencies.jar","./TestBundleJava/hue-0.1-jar-with-dependencies.jar", Copy("$TARGET", "$SOURCE")) Ignore("./TestBundleJava/hue-0.1-jar-with-dependencies.jar", "./TestBundleJava/hue-0.1-jar-with-dependencies.jar") -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': +if container_gtest_env.get('TEST') == '1': + if target_os in ['linux']: 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') diff --git a/service/resource-directory/SConscript b/service/resource-directory/SConscript index b6ef553c8..9244599de 100755 --- a/service/resource-directory/SConscript +++ b/service/resource-directory/SConscript @@ -1,3 +1,4 @@ +# -*- mode: python; python-indent-offset: 4; indent-tabs-mode: nil -*- #****************************************************************** # # Copyright 2015 Samsung Electronics All Rights Reserved. @@ -31,7 +32,7 @@ else: env.AppendUnique(CCFLAGS = ['-g']) if env.get('LOGGING'): - env.AppendUnique(CPPDEFINES = ['-DTB_LOG']) + env.AppendUnique(CPPDEFINES = ['TB_LOG']) lib_env = env.Clone() SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') diff --git a/service/resource-encapsulation/examples/linux/SConscript b/service/resource-encapsulation/examples/linux/SConscript index b8a6828e9..2dc07d59b 100644 --- a/service/resource-encapsulation/examples/linux/SConscript +++ b/service/resource-encapsulation/examples/linux/SConscript @@ -31,12 +31,12 @@ sample_env = lib_env.Clone() sample_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x']) sample_env.AppendUnique(LIBS = [ - 'rcs_common', - 'oc', - 'octbstack', - 'oc_logger', - 'connectivity_abstraction', 'coap', + 'connectivity_abstraction', + 'oc_logger', + 'octbstack', + 'oc', + 'rcs_common', 'pthread' ]) sample_env.AppendUnique(CPPPATH = ['../../include']) diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/SConscript b/service/resource-encapsulation/examples/linux/secureResourceExample/SConscript index 3ad2106b9..126309680 100644 --- a/service/resource-encapsulation/examples/linux/secureResourceExample/SConscript +++ b/service/resource-encapsulation/examples/linux/secureResourceExample/SConscript @@ -31,12 +31,12 @@ sample_env = lib_env.Clone() sample_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x']) sample_env.AppendUnique(LIBS = [ - 'rcs_common', - 'oc', - 'octbstack', - 'oc_logger', - 'connectivity_abstraction', 'coap', + 'connectivity_abstraction', + 'oc_logger', + 'octbstack', + 'oc', + 'rcs_common', 'pthread', 'tinydtls' ]) diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.dat b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.dat Binary files differindex 9de47b806..3c93b283c 100644 --- a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.dat +++ b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.dat diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.json b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.json index 5052bd118..792c3b184 100644 --- a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.json +++ b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.json @@ -8,38 +8,32 @@ {
"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": ""
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
},
{
"href": "/oic/ad",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.ad"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/acl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.acl"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 2
@@ -50,14 +44,14 @@ {
"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": 2
@@ -83,7 +77,7 @@ "deviceuuid": "32323232-3232-3232-3232-323232323232",
"devowneruuid": "32323232-3232-3232-3232-323232323232",
"rowneruuid": "32323232-3232-3232-3232-323232323232",
- "dpc": false
+ "x.org.iotivity.dpc": false
},
"cred": {
"creds": [
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.dat b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.dat Binary files differindex 31e18140a..706a03078 100644 --- a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.dat +++ b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.dat diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.json b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.json index 0e1bf23a1..d36503adf 100644 --- a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.json +++ b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.json @@ -8,38 +8,32 @@ {
"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": ""
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
},
{
"href": "/oic/ad",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.ad"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/acl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.acl"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 2
@@ -50,14 +44,14 @@ {
"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": 2
@@ -68,20 +62,20 @@ {
"href": "/a/light",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/a/light0",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/a/light1",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 6
@@ -107,7 +101,7 @@ "deviceuuid": "31313131-3131-3131-3131-313131313131",
"devowneruuid": "32323232-3232-3232-3232-323232323232",
"rowneruuid": "31313131-3131-3131-3131-313131313131",
- "dpc": false
+ "x.org.iotivity.dpc": false
},
"cred": {
"creds": [
diff --git a/service/resource-encapsulation/src/common/SConscript b/service/resource-encapsulation/src/common/SConscript index 06efb88ce..0f42d1dad 100644 --- a/service/resource-encapsulation/src/common/SConscript +++ b/service/resource-encapsulation/src/common/SConscript @@ -22,26 +22,25 @@ # rcs_common (primitiveResource and expiryTimer) build script ## import os -Import('env') -# Add third party libraries -lib_env = env.Clone() -SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', exports = 'lib_env') +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +lib_env = gtest_env.Clone() -src_dir = lib_env.get('SRC_DIR') -gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0' +# Add third party libraries +SConscript(lib_env.get('SRC_DIR') + '/service/third_party_libs.scons', exports = 'lib_env') rcs_common_env = lib_env.Clone() -target_os = env.get('TARGET_OS') - -release = env.get('RELEASE') +target_os = rcs_common_env.get('TARGET_OS') +release = rcs_common_env.get('RELEASE') +src_dir = rcs_common_env.get('SRC_DIR') ###################################################################### # Build flags ###################################################################### rcs_common_env.AppendUnique(CPPPATH = [ - env.get('SRC_DIR')+'/extlibs', + rcs_common_env.get('SRC_DIR')+'/extlibs', '../../include', 'primitiveResource/include']) @@ -49,7 +48,7 @@ rcs_common_env.AppendUnique(CPPPATH = [ 'expiryTimer/include', 'expiryTimer/src']) -rcs_common_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) +rcs_common_env.AppendUnique(LIBPATH = [rcs_common_env.get('BUILD_DIR')]) if target_os not in ['windows', 'winrt']: rcs_common_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall']) @@ -98,35 +97,31 @@ if target_os == 'linux': rcs_common_test_env = rcs_common_env.Clone(); rcs_common_test_env.PrependUnique(CPPPATH = [ - env.get('SRC_DIR')+'/extlibs/hippomocks-master', - gtest_dir + '/include', + rcs_common_test_env.get('SRC_DIR')+'/extlibs/hippomocks-master', 'utils/include' ]) - gtest = File(gtest_dir + '/lib/.libs/libgtest.a') - gtest_main = File(gtest_dir + '/lib/.libs/libgtest_main.a') - rcs_common_test_env.PrependUnique(LIBS = [ 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', 'rcs_common', - gtest, - gtest_main, + 'gtest', + 'gtest_main', 'pthread' ]) rcs_common_test_src = [ - env.Glob('primitiveResource/unittests/*.cpp'), + rcs_common_test_env.Glob('primitiveResource/unittests/*.cpp'), 'expiryTimer/unittests/ExpiryTimerTest.cpp' ] rcs_common_test = rcs_common_test_env.Program('rcs_common_test', rcs_common_test_src) Alias("rcs_common_test", rcs_common_test) - env.AppendTarget('rcs_common_test') + rcs_common_test_env.AppendTarget('rcs_common_test') - if env.get('TEST') == '1': + if rcs_common_test_env.get('TEST') == '1': from tools.scons.RunTest import * run_test(rcs_common_test_env, '', 'service/resource-encapsulation/src/common/rcs_common_test') diff --git a/service/resource-encapsulation/src/resourceBroker/unittest/SConscript b/service/resource-encapsulation/src/resourceBroker/unittest/SConscript index 34748b44b..c32470865 100644 --- a/service/resource-encapsulation/src/resourceBroker/unittest/SConscript +++ b/service/resource-encapsulation/src/resourceBroker/unittest/SConscript @@ -21,35 +21,31 @@ ## # ResourceBroker Unit Test build script ## +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +lib_env = gtest_env.Clone() -Import('env') - -if env.get('RELEASE'): - env.AppendUnique(CCFLAGS = ['-Os']) - env.AppendUnique(CPPDEFINES = ['NDEBUG']) +if lib_env.get('RELEASE'): + lib_env.AppendUnique(CCFLAGS = ['-Os']) + lib_env.AppendUnique(CPPDEFINES = ['NDEBUG']) else: - env.AppendUnique(CCFLAGS = ['-g']) + lib_env.AppendUnique(CCFLAGS = ['-g']) -if env.get('LOGGING'): - env.AppendUnique(CPPDEFINES = ['TB_LOG']) +if lib_env.get('LOGGING'): + lib_env.AppendUnique(CPPDEFINES = ['TB_LOG']) -lib_env = env.Clone() -SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') +SConscript('#service/third_party_libs.scons', 'lib_env') ###################################################################### #unit test setting ###################################################################### -src_dir = lib_env.get('SRC_DIR') -gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0' - broker_test_env = lib_env.Clone() -target_os = env.get('TARGET_OS') +src_dir = broker_test_env.get('SRC_DIR') +target_os = broker_test_env.get('TARGET_OS') ###################################################################### # Build flags ###################################################################### -gtest = File(gtest_dir + '/lib/.libs/libgtest.a') -gtest_main = File(gtest_dir + '/lib/.libs/libgtest_main.a') broker_test_env.AppendUnique(CPPPATH = ['../include']) broker_test_env.AppendUnique(CPPPATH = ['../../../include']) @@ -58,29 +54,37 @@ broker_test_env.AppendUnique(CPPPATH = ['../../common/expiryTimer/include']) broker_test_env.AppendUnique(CPPPATH = ['../../common/expiryTimer/src']) broker_test_env.AppendUnique(CPPPATH = ['../../common/utils/include']) -broker_test_env.PrependUnique(CPPPATH = [env.get('SRC_DIR')+'/extlibs/hippomocks-master', - gtest_dir + '/include']) -broker_test_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) -broker_test_env.PrependUnique(LIBS = ['rcs_client','rcs_common', 'oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', gtest, gtest_main]) +broker_test_env.PrependUnique(CPPPATH = [broker_test_env.get('SRC_DIR')+'/extlibs/hippomocks-master']) +broker_test_env.AppendUnique(LIBPATH = [broker_test_env.get('BUILD_DIR')]) + +broker_test_env.PrependUnique(LIBS = ['coap']) +broker_test_env.AppendUnique(LIBS = ['connectivity_abstraction']) +broker_test_env.AppendUnique(LIBS = ['oc_logger']) +broker_test_env.AppendUnique(LIBS = ['octbstack']) +broker_test_env.AppendUnique(LIBS = ['oc']) +broker_test_env.AppendUnique(LIBS = ['rcs_client']) +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']: +compiler = broker_test_env.get('CXX') +if 'g++' in compiler: broker_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x']) -if target_os == 'linux': +if target_os not in ['windows']: broker_test_env.AppendUnique(LIBS = ['pthread']) ###################################################################### # Build Test ###################################################################### -broker_test_src = env.Glob('./*.cpp') +broker_test_src = broker_test_env.Glob('./*.cpp') broker_test = broker_test_env.Program('broker_test', broker_test_src) Alias("broker_test", broker_test) -env.AppendTarget('broker_test') +broker_test_env.AppendTarget('broker_test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': +if broker_test_env.get('TEST') == '1': + if target_os in ['linux']: from tools.scons.RunTest import * run_test(broker_test_env, '', diff --git a/service/resource-encapsulation/src/resourceCache/unittests/SConscript b/service/resource-encapsulation/src/resourceCache/unittests/SConscript index 7a7d992db..57f5e18a1 100644 --- a/service/resource-encapsulation/src/resourceCache/unittests/SConscript +++ b/service/resource-encapsulation/src/resourceCache/unittests/SConscript @@ -22,34 +22,31 @@ # ResourceCache Unit Test build script ## -Import('env') +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +lib_env = gtest_env.Clone() -if env.get('RELEASE'): - env.AppendUnique(CCFLAGS = ['-Os']) - env.AppendUnique(CPPDEFINES = ['NDEBUG']) + +if lib_env.get('RELEASE'): + lib_env.AppendUnique(CCFLAGS = ['-Os']) + lib_env.AppendUnique(CPPDEFINES = ['NDEBUG']) else: - env.AppendUnique(CCFLAGS = ['-g']) + lib_env.AppendUnique(CCFLAGS = ['-g']) -if env.get('LOGGING'): - env.AppendUnique(CPPDEFINES = ['TB_LOG']) +if lib_env.get('LOGGING'): + lib_env.AppendUnique(CPPDEFINES = ['TB_LOG']) -lib_env = env.Clone() -SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') +SConscript(lib_env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') ###################################################################### # unit test setting ###################################################################### -src_dir = lib_env.get('SRC_DIR') -gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0' - cache_test_env = lib_env.Clone() -target_os = env.get('TARGET_OS') +target_os = cache_test_env.get('TARGET_OS') ###################################################################### # Build flags ###################################################################### -gtest = File(gtest_dir + '/lib/.libs/libgtest.a') -gtest_main = File(gtest_dir + '/lib/.libs/libgtest_main.a') cache_test_env.AppendUnique(CPPPATH = ['../include']) cache_test_env.AppendUnique(CPPPATH = ['../../../include']) @@ -57,10 +54,9 @@ cache_test_env.AppendUnique(CPPPATH = ['../../common/primitiveResource/include'] cache_test_env.AppendUnique(CPPPATH = ['../../common/expiryTimer/include']) cache_test_env.AppendUnique(CPPPATH = ['../../common/expiryTimer/src']) cache_test_env.AppendUnique(CPPPATH = ['../../common/utils/include']) -cache_test_env.PrependUnique(CPPPATH = [env.get('SRC_DIR')+'/extlibs/hippomocks-master', - gtest_dir + '/include']) -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]) +cache_test_env.PrependUnique(CPPPATH = [cache_test_env.get('SRC_DIR')+'/extlibs/hippomocks-master']) +cache_test_env.AppendUnique(LIBPATH = [cache_test_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']: cache_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x']) @@ -71,15 +67,14 @@ if target_os == 'linux': ###################################################################### # Build Test ###################################################################### -cache_test_src = env.Glob('./*.cpp') +cache_test_src = cache_test_env.Glob('./*.cpp') cache_test = cache_test_env.Program('cache_test', cache_test_src) Alias("cache_test", cache_test) -env.AppendTarget('cache_test') +cache_test_env.AppendTarget('cache_test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') +if cache_test_env.get('TEST') == '1': if target_os == 'linux': 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') diff --git a/service/resource-encapsulation/src/serverBuilder/SConscript b/service/resource-encapsulation/src/serverBuilder/SConscript index 563d1d64e..492cf9966 100644 --- a/service/resource-encapsulation/src/serverBuilder/SConscript +++ b/service/resource-encapsulation/src/serverBuilder/SConscript @@ -21,21 +21,17 @@ ## # rcs_server (Server Builder) project build script ## -import os -Import('env') +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +lib_env = gtest_env.Clone() # Add third party libraries -lib_env = env.Clone() -SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', exports = 'lib_env') - -src_dir = lib_env.get('SRC_DIR') - -gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0' - +SConscript('#service/third_party_libs.scons', exports = 'lib_env') server_builder_env = lib_env.Clone() -target_os = env.get('TARGET_OS') +release = server_builder_env.get('RELEASE') +src_dir = server_builder_env.get('SRC_DIR') +target_os = server_builder_env.get('TARGET_OS') -release = env.get('RELEASE') ###################################################################### # Build flags @@ -46,25 +42,24 @@ server_builder_env.AppendUnique(CPPPATH = [ '../../include', ]) -server_builder_env.AppendUnique(CPPPATH = [env.get('SRC_DIR')+'/extlibs', 'include']) - -server_builder_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) +server_builder_env.AppendUnique(CPPPATH = [server_builder_env.get('SRC_DIR')+'/extlibs', 'include']) +server_builder_env.AppendUnique(LIBPATH = [server_builder_env.get('BUILD_DIR')]) +server_builder_env.AppendUnique(LIBS = ['oc', 'rcs_common']) if target_os not in ['windows', 'winrt']: server_builder_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall']) - if target_os != 'android': + if target_os not in ['android']: + server_builder_env.AppendUnique(LIBS = ['dl']) server_builder_env.AppendUnique(CXXFLAGS = ['-pthread']) if target_os not in ['darwin', 'ios', 'windows', 'winrt']: server_builder_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined']) -if target_os == 'android': +if target_os in ['android']: server_builder_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions']) server_builder_env.PrependUnique(LIBS = ['gnustl_shared', 'log']) -server_builder_env.AppendUnique(LIBS = ['dl', 'oc', 'rcs_common']) - -if env.get('LOGGING'): +if server_builder_env.get('LOGGING'): server_builder_env.AppendUnique(LIBS = ['octbstack']) if not release: @@ -74,7 +69,7 @@ if not release: ###################################################################### # Source files and Targets ###################################################################### -server_builder_src = env.Glob('src/*.cpp') +server_builder_src = server_builder_env.Glob('src/*.cpp') server_builder_static = server_builder_env.StaticLibrary('rcs_server', server_builder_src) server_builder_shared = server_builder_env.SharedLibrary('rcs_server', server_builder_src) @@ -85,36 +80,32 @@ server_builder_env.UserInstallTargetLib([server_builder_static, server_builder_s ###################################################################### # Build Test ###################################################################### -if target_os == 'linux': +if target_os in ['linux']: server_builder_test_env = server_builder_env.Clone(); server_builder_test_env.AppendUnique(CPPPATH = [ - env.get('SRC_DIR')+'/extlibs/hippomocks-master', - gtest_dir + '/include', + server_builder_test_env.get('SRC_DIR')+'/extlibs/hippomocks-master', '../common/utils/include' ]) - gtest = File(gtest_dir + '/lib/.libs/libgtest.a') - gtest_main = File(gtest_dir + '/lib/.libs/libgtest_main.a') - server_builder_test_env.PrependUnique(LIBS = [ 'rcs_server', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', - gtest, - gtest_main, + 'gtest', + 'gtest_main', 'pthread', ]) - server_builder_test_src = env.Glob('unittests/*.cpp') + server_builder_test_src = server_builder_test_env.Glob('unittests/*.cpp') server_builder_test = server_builder_test_env.Program('rcs_server_test', server_builder_test_src) Alias("rcs_server_test", server_builder_test) - env.AppendTarget('rcs_server_test') + server_builder_test_env.AppendTarget('rcs_server_test') - if env.get('TEST') == '1': + if server_builder_test_env.get('TEST') == '1': from tools.scons.RunTest import * run_test(server_builder_test_env, '', 'service/resource-encapsulation/src/serverBuilder/rcs_server_test') diff --git a/service/resource-encapsulation/unittests/SConscript b/service/resource-encapsulation/unittests/SConscript index 67855cf3d..5be4965c1 100644 --- a/service/resource-encapsulation/unittests/SConscript +++ b/service/resource-encapsulation/unittests/SConscript @@ -18,34 +18,30 @@ # #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +lib_env = gtest_env.Clone() + ## # ResourceClient Unit Test build script ## -import os -Import('env') - -if env.get('RELEASE'): - env.AppendUnique(CCFLAGS = ['-Os']) - env.AppendUnique(CPPDEFINES = ['NDEBUG']) +if lib_env.get('RELEASE'): + lib_env.AppendUnique(CCFLAGS = ['-Os']) + lib_env.AppendUnique(CPPDEFINES = ['NDEBUG']) else: - env.AppendUnique(CCFLAGS = ['-g']) + lib_env.AppendUnique(CCFLAGS = ['-g']) -if env.get('LOGGING'): - env.AppendUnique(CPPDEFINES = ['TB_LOG']) +if lib_env.get('LOGGING'): + lib_env.AppendUnique(CPPDEFINES = ['TB_LOG']) # Add third party libraries -lib_env = env.Clone() -SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') +SConscript(lib_env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') -target_os = env.get('TARGET_OS') +target_os = lib_env.get('TARGET_OS') if target_os == 'linux': - # Verify that 'google unit test' library is installed. If not, - # get it and install it - SConscript(env.get('SRC_DIR') + '/extlibs/gtest/SConscript') - # Verify that 'hippomocks' mocking code is installed. If not, # get it and install it - SConscript(env.get('SRC_DIR') + '/extlibs/hippomocks.scons') + SConscript(lib_env.get('SRC_DIR') + '/extlibs/hippomocks.scons') rcs_test_env = lib_env.Clone() @@ -53,18 +49,13 @@ rcs_test_env = lib_env.Clone() #unit test setting ###################################################################### src_dir = lib_env.get('SRC_DIR') -gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0' ###################################################################### # Build flags ###################################################################### -gtest = File(gtest_dir + '/lib/.libs/libgtest.a') -gtest_main = File(gtest_dir + '/lib/.libs/libgtest_main.a') - rcs_test_env.AppendUnique( CPPPATH = [ src_dir + '/extlibs/hippomocks-master', - src_dir + '/extlibs/gtest/gtest-1.7.0/include', '../include', '../src/common/utils/include', ]) @@ -76,30 +67,30 @@ if target_os not in ['windows', 'winrt']: rcs_test_env.AppendUnique(LIBS = ['pthread']) rcs_test_env.PrependUnique(LIBS = [ + 'connectivity_abstraction', + 'oc_logger', + 'oc_logger_core', + 'octbstack', + 'oc', 'rcs_client', 'rcs_server', 'rcs_common', - 'oc', - 'octbstack', - 'oc_logger', - 'oc_logger_core', - 'connectivity_abstraction', - gtest, - gtest_main]) + 'gtest', + 'gtest_main']) rcs_test_env.AppendUnique(LIBS = ['dl']) ###################################################################### # Build Test ###################################################################### -rcs_test_src = env.Glob('./*.cpp') +rcs_test_src = rcs_test_env.Glob('./*.cpp') rcs_client_test = rcs_test_env.Program('rcs_client_test', rcs_test_src) Alias("rcs_client_test", rcs_client_test) -env.AppendTarget('rcs_client_test') +rcs_test_env.AppendTarget('rcs_client_test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') +if rcs_test_env.get('TEST') == '1': + target_os = rcs_test_env.get('TARGET_OS') if target_os == 'linux': from tools.scons.RunTest import * - run_test(rcs_test_env, '', 'service/resource-encapsulation/unittests/rcs_client_test')
\ No newline at end of file + run_test(rcs_test_env, '', 'service/resource-encapsulation/unittests/rcs_client_test') diff --git a/service/resource-hosting/SampleApp/linux/SConscript b/service/resource-hosting/SampleApp/linux/SConscript index 1062275f3..6b8f13249 100644 --- a/service/resource-hosting/SampleApp/linux/SConscript +++ b/service/resource-hosting/SampleApp/linux/SConscript @@ -17,23 +17,23 @@ resourcehosting_env.AppendUnique(CPPPATH = ['../../../../resource/csdk/connectiv resourcehosting_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x']) resourcehosting_sample_env = resourcehosting_env.Clone() resourcehosting_env.AppendUnique(LIBS = [ + 'coap', + 'connectivity_abstraction', + 'oc_logger', + 'octbstack', + 'oc', 'resource_hosting', 'rcs_client', 'rcs_server', 'rcs_common', - 'oc', - 'octbstack', - 'oc_logger', - 'connectivity_abstraction', - 'coap', 'pthread' ]) resourcehosting_sample_env.AppendUnique(LIBS = [ - 'oc', - 'octbstack', - 'oc_logger', 'connectivity_abstraction', 'coap', + 'oc_logger', + 'octbstack', + 'oc', 'pthread' ]) diff --git a/service/resource-hosting/unittest/SConscript b/service/resource-hosting/unittest/SConscript index 2b15b0a4c..f7bab0c0d 100644 --- a/service/resource-hosting/unittest/SConscript +++ b/service/resource-hosting/unittest/SConscript @@ -21,52 +21,48 @@ ## # ResourceHosting Unit Test build script ## +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +lib_env = gtest_env.Clone() -Import('env') - -if env.get('RELEASE'): - env.AppendUnique(CCFLAGS = ['-Os']) - env.AppendUnique(CPPDEFINES = ['NDEBUG']) +if lib_env.get('RELEASE'): + lib_env.AppendUnique(CCFLAGS = ['-Os']) + lib_env.AppendUnique(CPPDEFINES = ['NDEBUG']) else: - env.AppendUnique(CCFLAGS = ['-g']) + lib_env.AppendUnique(CCFLAGS = ['-g']) + +if lib_env.get('LOGGING'): + lib_env.AppendUnique(CPPDEFINES = ['TB_LOG']) -if env.get('LOGGING'): - env.AppendUnique(CPPDEFINES = ['TB_LOG']) -lib_env = env.Clone() -SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') +SConscript('#service/third_party_libs.scons', 'lib_env') ###################################################################### #unit test setting ###################################################################### src_dir = lib_env.get('SRC_DIR') -gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0' hosting_test_env = lib_env.Clone() -target_os = env.get('TARGET_OS') +target_os = hosting_test_env.get('TARGET_OS') ###################################################################### # Build flags ###################################################################### -GTest = File(gtest_dir + '/lib/.libs/libgtest.a') -GTest_Main = File(gtest_dir + '/lib/.libs/libgtest_main.a') -#hosting_test_env.AppendUnique(LIBPATH = [gtest_dir + '/lib/.libs']) -hosting_test_env.AppendUnique(LIBPATH = [lib_env.get('BUILD_DIR')]) +hosting_test_env.AppendUnique(LIBPATH = [hosting_test_env.get('BUILD_DIR')]) hosting_test_env.AppendUnique(LIBS = [ 'resource_hosting', 'rcs_server', 'rcs_client','rcs_common', 'oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', - GTest_Main, GTest]) + 'gtest_main', 'gtest']) if target_os not in ['windows', 'winrt']: hosting_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x']) -if target_os == 'linux': - hosting_test_env.AppendUnique(CXXFLAGS = ['-pthread']) - hosting_test_env.AppendUnique(LIBS = ['pthread']) +if target_os in ['linux']: + hosting_test_env.AppendUnique(CXXFLAGS = ['-pthread']) + hosting_test_env.AppendUnique(LIBS = ['pthread']) -hosting_test_env.PrependUnique(CPPPATH = [ src_dir + '/extlibs/hippomocks-master', - gtest_dir + '/include']) +hosting_test_env.PrependUnique(CPPPATH = [ src_dir + '/extlibs/hippomocks-master']) hosting_test_env.AppendUnique(CPPPATH = ['../src']) hosting_test_env.AppendUnique(CPPPATH = ['../../resource-encapsulation/include']) hosting_test_env.AppendUnique(CPPPATH = ['../../resource-encapsulation/src/common/primitiveResource/include']) @@ -75,13 +71,14 @@ hosting_test_env.AppendUnique(CPPPATH = ['../../resource-encapsulation/src/commo # Build Test ###################################################################### -hosting_test_src = env.Glob('./*.cpp') +hosting_test_src = hosting_test_env.Glob('./*.cpp') hosting_test = hosting_test_env.Program('hosting_test', hosting_test_src) Alias("hosting_test", hosting_test) -env.AppendTarget('hosting_test') +hosting_test_env.AppendTarget('hosting_test') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': +if hosting_test_env.get('TEST') == '1': + target_os = hosting_test_env.get('TARGET_OS') + if target_os in ['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') + diff --git a/service/scene-manager/SConscript b/service/scene-manager/SConscript index 9348578b3..d3511040a 100755 --- a/service/scene-manager/SConscript +++ b/service/scene-manager/SConscript @@ -50,14 +50,14 @@ scenemanager_env.AppendUnique(CPPPATH = ['../resource-encapsulation/src/common/e scenemanager_env.PrependUnique(LIBS = [ + 'coap', + 'connectivity_abstraction', + 'oc_logger', + 'octbstack', + 'oc', 'rcs_client', 'rcs_server', - 'rcs_common', - 'oc', - 'octbstack', - 'oc_logger', - 'connectivity_abstraction', - 'libcoap' + 'rcs_common' ]) if target_os not in ['windows', 'winrt']: diff --git a/service/scene-manager/sampleapp/linux/SConscript b/service/scene-manager/sampleapp/linux/SConscript index 6946510be..8753303e6 100755 --- a/service/scene-manager/sampleapp/linux/SConscript +++ b/service/scene-manager/sampleapp/linux/SConscript @@ -18,15 +18,15 @@ scenemanager_sample_env.AppendUnique(CPPPATH = ['../../../../resource/csdk/conne scenemanager_sample_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x']) scenemanager_sample_env.AppendUnique(LIBS = [ + 'oc_logger', + 'coap', + 'connectivity_abstraction', 'scene_manager', 'rcs_client', 'rcs_server', 'rcs_common', - 'oc', 'octbstack', - 'oc_logger', - 'connectivity_abstraction', - 'coap', + 'oc', 'pthread' ]) @@ -45,4 +45,4 @@ if not env.get('RELEASE'): sceneserver = scenemanager_sample_env.Program('sceneserver', 'sceneserver.cpp') sceneclient = scenemanager_sample_env.Program('sceneclient', 'sceneclient.cpp') fanserver = scenemanager_sample_env.Program('fanserver', 'fanserver.cpp') -lightserver = scenemanager_sample_env.Program('lightserver', 'lightserver.cpp')
\ No newline at end of file +lightserver = scenemanager_sample_env.Program('lightserver', 'lightserver.cpp') diff --git a/service/scene-manager/unittests/SConscript b/service/scene-manager/unittests/SConscript index 25d65d811..4be9ccd62 100755 --- a/service/scene-manager/unittests/SConscript +++ b/service/scene-manager/unittests/SConscript @@ -18,45 +18,41 @@ # #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +lib_env = gtest_env.Clone() + ## # SceneManager Unit Test build script ## - -Import('env') - -if env.get('RELEASE'): - env.AppendUnique(CCFLAGS = ['-Os']) - env.AppendUnique(CPPDEFINES = ['NDEBUG']) +if lib_env.get('RELEASE'): + lib_env.AppendUnique(CCFLAGS = ['-Os']) + lib_env.AppendUnique(CPPDEFINES = ['NDEBUG']) else: - env.AppendUnique(CCFLAGS = ['-g']) + lib_env.AppendUnique(CCFLAGS = ['-g']) -if env.get('LOGGING'): - env.AppendUnique(CPPDEFINES = ['TB_LOG']) +if lib_env.get('LOGGING'): + lib_env.AppendUnique(CPPDEFINES = ['TB_LOG']) -lib_env = env.Clone() -SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') +SConscript(lib_env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') ###################################################################### #unit test setting ###################################################################### src_dir = lib_env.get('SRC_DIR') -gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0' scene_test_env = lib_env.Clone() -target_os = env.get('TARGET_OS') +target_os = scene_test_env.get('TARGET_OS') ###################################################################### # Build flags ###################################################################### -GTest = File(gtest_dir + '/lib/.libs/libgtest.a') -GTest_Main = File(gtest_dir + '/lib/.libs/libgtest_main.a') -#scene_test_env.AppendUnique(LIBPATH = [gtest_dir + '/lib/.libs']) scene_test_env.AppendUnique(LIBPATH = [lib_env.get('BUILD_DIR')]) scene_test_env.AppendUnique(LIBS = [ 'scene_manager', 'rcs_server', 'rcs_client','rcs_common', 'oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', - GTest_Main, GTest]) + 'gtest_main', 'gtest']) if target_os not in ['windows', 'winrt']: scene_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x']) @@ -65,12 +61,11 @@ if target_os == 'linux': scene_test_env.AppendUnique(CXXFLAGS = ['-pthread']) scene_test_env.AppendUnique(LIBS = ['pthread']) -if not env.get('RELEASE'): +if not scene_test_env.get('RELEASE'): scene_test_env.PrependUnique(LIBS = ['gcov']) scene_test_env.AppendUnique(CXXFLAGS = ['--coverage']) -scene_test_env.PrependUnique(CPPPATH = [ src_dir + '/extlibs/hippomocks-master', - gtest_dir + '/include']) +scene_test_env.PrependUnique(CPPPATH = [ src_dir + '/extlibs/hippomocks-master']) scene_test_env.AppendUnique(CPPPATH = ['../include']) scene_test_env.AppendUnique(CPPPATH = ['../src']) scene_test_env.AppendUnique(CPPPATH = ['../../resource-encapsulation/include']) @@ -80,53 +75,53 @@ scene_test_env.AppendUnique(CPPPATH = ['../../resource-encapsulation/src/common/ # Build Test ###################################################################### -scene_list_test_src = env.Glob('./SceneListTest.cpp') +scene_list_test_src = scene_test_env.Glob('./SceneListTest.cpp') scene_list_test = scene_test_env.Program('scene_list_test', scene_list_test_src) Alias("scene_list_test", scene_list_test) -env.AppendTarget('scene_list_test') +scene_test_env.AppendTarget('scene_list_test') scene_test_env.InstallTarget(scene_list_test, 'scene_list_test') -scene_collection_test_src = env.Glob('./SceneCollectionTest.cpp') +scene_collection_test_src = scene_test_env.Glob('./SceneCollectionTest.cpp') scene_collection_test = scene_test_env.Program('scene_collection_test', scene_collection_test_src) Alias("scene_collection_test", scene_collection_test) -env.AppendTarget('scene_collection_test') +scene_test_env.AppendTarget('scene_collection_test') scene_test_env.InstallTarget(scene_collection_test, 'scene_collection_test') -scene_test_src = env.Glob('./SceneTest.cpp') +scene_test_src = scene_test_env.Glob('./SceneTest.cpp') scene_test = scene_test_env.Program('scene_test', scene_test_src) Alias("scene_test", scene_test) -env.AppendTarget('scene_test') +scene_test_env.AppendTarget('scene_test') scene_test_env.InstallTarget(scene_test, 'scene_test') -scene_action_test_src = env.Glob('./SceneActionTest.cpp') +scene_action_test_src = scene_test_env.Glob('./SceneActionTest.cpp') scene_action_test = scene_test_env.Program('scene_action_test', scene_action_test_src) Alias("scene_action_test", scene_action_test) -env.AppendTarget('scene_action_test') +scene_test_env.AppendTarget('scene_action_test') scene_test_env.InstallTarget(scene_action_test, 'scene_action_test') -remote_scene_list_test_src = env.Glob('./RemoteSceneListTest.cpp') +remote_scene_list_test_src = scene_test_env.Glob('./RemoteSceneListTest.cpp') remote_scene_list_test = scene_test_env.Program('remote_scene_list_test', remote_scene_list_test_src) Alias("remote_scene_list_test", remote_scene_list_test) -env.AppendTarget('remote_scene_list_test') +scene_test_env.AppendTarget('remote_scene_list_test') -remote_scene_col_test_src = env.Glob('./RemoteSceneCollectionTest.cpp') +remote_scene_col_test_src = scene_test_env.Glob('./RemoteSceneCollectionTest.cpp') remote_scene_col_test = scene_test_env.Program('remote_scene_col_test', remote_scene_col_test_src) Alias("remote_scene_col_test", remote_scene_col_test) -env.AppendTarget('remote_scene_col_test') +scene_test_env.AppendTarget('remote_scene_col_test') -remote_scene_test_src = env.Glob('./RemoteSceneTest.cpp') +remote_scene_test_src = scene_test_env.Glob('./RemoteSceneTest.cpp') remote_scene_test = scene_test_env.Program('remote_scene_test', remote_scene_test_src) Alias("remote_scene_test", remote_scene_test) -env.AppendTarget('remote_scene_test') +scene_test_env.AppendTarget('remote_scene_test') -remote_scene_action_test_src = env.Glob('./RemoteSceneActionTest.cpp') +remote_scene_action_test_src = scene_test_env.Glob('./RemoteSceneActionTest.cpp') remote_scene_action_test = scene_test_env.Program('remote_scene_action_test', remote_scene_action_test_src) Alias("remote_scene_action_test", remote_scene_action_test) -env.AppendTarget('remote_scene_action_test') +scene_test_env.AppendTarget('remote_scene_action_test') -#target_os = env.get('TARGET_OS') +#target_os = scene_test_env.get('TARGET_OS') #if target_os == 'linux': # 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') diff --git a/service/scene-manager/unittests/SceneTest.cpp b/service/scene-manager/unittests/SceneTest.cpp index fc1ec4c77..80f250e07 100755 --- a/service/scene-manager/unittests/SceneTest.cpp +++ b/service/scene-manager/unittests/SceneTest.cpp @@ -142,8 +142,16 @@ TEST_F(SceneTest, getAllSceneInstance) for(const auto &it : scenes) { - ASSERT_EQ(it.first, sceneNames.at(count++)); + for (const auto &name : sceneNames) + { + if(it.first == name) + { + count++; + break; + } + } } + ASSERT_EQ(count, 2); } TEST_F(SceneTest, getSceneActionUsingRemoteResource) @@ -197,4 +205,4 @@ TEST_F(SceneTest, executeSceneUsingEmptyCallback) pScene1->addNewSceneAction(pRemoteResource2, KEY_2, VALUE_2); ASSERT_THROW(pScene1->execute(nullptr), RCSInvalidParameterException); -}
\ No newline at end of file +} diff --git a/service/simulator/examples/client/simulator_client.cpp b/service/simulator/examples/client/simulator_client.cpp index a8f9f8f97..229de740d 100644 --- a/service/simulator/examples/client/simulator_client.cpp +++ b/service/simulator/examples/client/simulator_client.cpp @@ -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; diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ResourceManager.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ResourceManager.java index dc1165431..44fc3eedc 100644 --- a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ResourceManager.java +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ResourceManager.java @@ -590,12 +590,21 @@ public class ResourceManager { } // Set the resource interfaces. - jSimulatorSingleResource - .setInterface(Utility.convertSetToVectorString(resource - .getResourceInterfaces())); + Set<String> interfaces = resource.getResourceInterfaces(); + if (null != interfaces && !interfaces.isEmpty()) { + jSimulatorSingleResource.setInterface(Utility + .convertSetToVectorString(resource + .getResourceInterfaces())); + } // Register the resource with the platform. jSimulatorSingleResource.start(); + + // Read the interfaces from the native layer and set it to the + // interface list. + resource.setResourceInterfaces(Utility + .convertVectorToSet(jSimulatorSingleResource.getInterface())); + resource.setStarted(true); } catch (SimulatorException e) { Activator diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Utility.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Utility.java index a6628745c..dcf10e418 100644 --- a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Utility.java +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Utility.java @@ -577,7 +577,6 @@ public class Utility { Map<String, String> ifTypes = null; if (resourceClass == SingleResource.class) { ifTypes = new HashMap<String, String>(); - ifTypes.put(Constants.BASELINE_INTERFACE, "Baseline"); ifTypes.put(Constants.READ_ONLY_INTERFACE, "Read-Only"); ifTypes.put(Constants.READ_WRITE_INTERFACE, "Read-Write"); ifTypes.put(Constants.ACTUATOR_INTERFACE, "Actuator"); diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MetaPropertiesView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MetaPropertiesView.java index d5fd2d67a..b362e2e0b 100644 --- a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MetaPropertiesView.java +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MetaPropertiesView.java @@ -223,6 +223,8 @@ public class MetaPropertiesView extends ViewPart { // interface set. Set<String> curIfSet = resourceInSelection .getResourceInterfaces(); + // Adding default interface to local set if removed. + updatedIfSet.add(Constants.BASELINE_INTERFACE); if (null != curIfSet && null != updatedIfSet) { if (curIfSet.size() != updatedIfSet.size()) { update = true; @@ -506,7 +508,13 @@ public class MetaPropertiesView extends ViewPart { } // Update the model MetaProperty prop = (MetaProperty) element; - prop.setPropValue(newPropValue.toString()); + StringBuilder value = new StringBuilder(); + value.append(Constants.BASELINE_INTERFACE); + if (newPropValue.length() > 0) { + value.append(", " + newPropValue.toString()); + } + prop.setPropValue(value.toString()); + // Update the viewer in a separate UI thread. Display.getDefault().asyncExec(new Runnable() { @Override diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdateResourceInterfaceDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdateResourceInterfaceDialog.java index 4fe07b558..09a40073a 100644 --- a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdateResourceInterfaceDialog.java +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdateResourceInterfaceDialog.java @@ -17,7 +17,6 @@ package oic.simulator.serviceprovider.view.dialogs; import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.TrayDialog; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; @@ -36,8 +35,6 @@ import org.eclipse.swt.widgets.Shell; import java.util.ArrayList; import java.util.Map; -import oic.simulator.serviceprovider.utils.Constants; - /** * Dialog for starting and stopping the automatic verifications. */ @@ -197,23 +194,15 @@ public class UpdateResourceInterfaceDialog extends TrayDialog { @Override protected void okPressed() { - String[] items = ifTypesList.getItems(); - if (null == items || items.length == 0) { - MessageDialog - .openInformation( - getShell(), - "Default Interface Type Selection", - "As no interface types are added, the resource will be " - + "configured with the default interface type(oic.if.baseline)."); - ifTypesList.add("Baseline" + " (" - + Constants.DEFAULT_SINGLE_RESOURCE_INTERFACE + ")"); - } - // Clearing the map to freshly add selected items. updatedResInterfaces.clear(); - for (String item : ifTypesList.getItems()) { - String value = supportedResInterfaces.get(item); - updatedResInterfaces.put(item, value); + + String[] items = ifTypesList.getItems(); + if (null != items && items.length > 0) { + for (String item : items) { + String value = supportedResInterfaces.get(item); + updatedResInterfaces.put(item, value); + } } close(); } diff --git a/service/simulator/src/server/oc_interface_details.cpp b/service/simulator/src/server/oc_interface_details.cpp index b32f1f69d..96f1599fc 100644 --- a/service/simulator/src/server/oc_interface_details.cpp +++ b/service/simulator/src/server/oc_interface_details.cpp @@ -39,7 +39,7 @@ bool OCInterfaceDetails::isInterface(const std::string &interfaceType) { if (m_interfaces.end() != m_interfaces.find(interfaceType)) return true; - return true; + return false; } bool OCInterfaceDetails::isRequestSupported(const std::string &interfaceType, diff --git a/service/simulator/src/server/simulator_single_resource_impl.cpp b/service/simulator/src/server/simulator_single_resource_impl.cpp index 5cc5c87f7..2539d2289 100755 --- a/service/simulator/src/server/simulator_single_resource_impl.cpp +++ b/service/simulator/src/server/simulator_single_resource_impl.cpp @@ -79,6 +79,12 @@ void SimulatorSingleResourceImpl::setInterface(const std::string &interfaceType) { VALIDATE_INPUT(interfaceType.empty(), "Interface type list is empty!") + if (false == OCInterfaceDetails::getInstance()->isInterface(interfaceType)) + { + OIC_LOG(ERROR, TAG, "Request is not OIC spec defined!"); + return; + } + std::lock_guard<std::recursive_mutex> lock(m_objectLock); if (m_resourceHandle) { @@ -86,7 +92,8 @@ void SimulatorSingleResourceImpl::setInterface(const std::string &interfaceType) "Resource interface can not be reset when resource is started!"); } - m_interfaces = {interfaceType}; + if (interfaceType != OC::DEFAULT_INTERFACE) + m_interfaces = {OC::DEFAULT_INTERFACE, interfaceType}; } void SimulatorSingleResourceImpl::setInterface(const std::vector<std::string> &interfaceTypes) @@ -100,9 +107,12 @@ void SimulatorSingleResourceImpl::setInterface(const std::vector<std::string> &i "Resource interface can not be reset when resource is started!"); } - m_interfaces.clear(); + m_interfaces = {OC::DEFAULT_INTERFACE}; for (auto &interfaceType : interfaceTypes) { + if (false == OCInterfaceDetails::getInstance()->isInterface(interfaceType)) + continue; + if (m_interfaces.end() == std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType)) { @@ -115,6 +125,12 @@ void SimulatorSingleResourceImpl::addInterface(const std::string &interfaceType) { VALIDATE_INPUT(interfaceType.empty(), "Interface type is empty!") + if (false == OCInterfaceDetails::getInstance()->isInterface(interfaceType)) + { + OIC_LOG(ERROR, TAG, "Request is not OIC spec defined!"); + return; + } + if (m_interfaces.end() != std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType)) { SIM_LOG(ILogger::ERROR, "[" << m_uri << "] " diff --git a/service/things-manager/sampleapp/linux/configuration/SConscript b/service/things-manager/sampleapp/linux/configuration/SConscript index 7285e13d3..f9ccdf9c1 100644 --- a/service/things-manager/sampleapp/linux/configuration/SConscript +++ b/service/things-manager/sampleapp/linux/configuration/SConscript @@ -39,9 +39,15 @@ linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/src']) 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 = ['libTGMSDKLibrary', 'oc', 'octbstack', - 'connectivity_abstraction', - 'libcoap', 'liboc_logger', 'dl', 'pthread']) +linux_sample_env.PrependUnique(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 = ['libTGMSDKLibrary']) +linux_sample_env.AppendUnique(LIBS = ['dl']) +linux_sample_env.AppendUnique(LIBS = ['pthread']) + if env.get('SECURED') == '1': linux_sample_env.AppendUnique(LIBS = ['tinydtls']) diff --git a/service/things-manager/unittests/SConscript b/service/things-manager/unittests/SConscript index e1bd78471..a906d5e36 100644 --- a/service/things-manager/unittests/SConscript +++ b/service/things-manager/unittests/SConscript @@ -22,83 +22,75 @@ # ThingsManager Unit Test build script ## import os -Import('env') -if env.get('RELEASE'): - env.AppendUnique(CCFLAGS = ['-Os']) - env.AppendUnique(CPPDEFINES = ['NDEBUG']) +# SConscript file for Local PKI google tests +gtest_env = SConscript('#extlibs/gtest/SConscript') +lib_env = gtest_env.Clone() +target_os = lib_env.get('TARGET_OS') + +if lib_env.get('RELEASE'): + lib_env.AppendUnique(CCFLAGS = ['-Os']) + lib_env.AppendUnique(CPPDEFINES = ['NDEBUG']) else: - env.AppendUnique(CCFLAGS = ['-g']) + lib_env.AppendUnique(CCFLAGS = ['-g']) -if env.get('LOGGING'): - env.AppendUnique(CPPDEFINES = ['TB_LOG']) +if lib_env.get('LOGGING'): + lib_env.AppendUnique(CPPDEFINES = ['TB_LOG']) # Add third party libraries -lib_env = env.Clone() -SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') - -target_os = env.get('TARGET_OS') -if target_os == 'linux': - # Verify that 'google unit test' library is installed. If not, - # get it and install it - SConscript(env.get('SRC_DIR') + '/extlibs/gtest/SConscript') +SConscript('#service/third_party_libs.scons', 'lib_env') - # Verify that 'hippomocks' mocking code is installed. If not, - # get it and install it - SConscript(env.get('SRC_DIR') + '/extlibs/hippomocks.scons') +if target_os in ['linux']: + # Verify that 'hippomocks' mocking code is installed. + # If not, get it and install it + SConscript('#extlibs/hippomocks.scons') ThingsManager_gtest_env = lib_env.Clone() ###################################################################### #unit test setting ###################################################################### -src_dir = lib_env.get('SRC_DIR') -gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0' +src_dir = ThingsManager_gtest_env.get('SRC_DIR') ###################################################################### # Build flags ###################################################################### -gtest = File(gtest_dir + '/lib/.libs/libgtest.a') -gtest_main = File(gtest_dir + '/lib/.libs/libgtest_main.a') - ThingsManager_gtest_env.AppendUnique( CPPPATH = [ src_dir + '/extlibs/hippomocks-master', - src_dir + '/extlibs/gtest/gtest-1.7.0/include', '../sdk/inc', '../../../extlibs/timer' ]) if target_os not in ['windows', 'winrt']: - ThingsManager_gtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall']) - if target_os != 'android': - ThingsManager_gtest_env.AppendUnique(CXXFLAGS = ['-pthread']) - ThingsManager_gtest_env.AppendUnique(LIBS = ['pthread']) + ThingsManager_gtest_env.AppendUnique(LIBS = ['dl']) + ThingsManager_gtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall']) + if target_os != 'android': + ThingsManager_gtest_env.AppendUnique(CXXFLAGS = ['-pthread']) + ThingsManager_gtest_env.AppendUnique(LIBS = ['pthread']) ThingsManager_gtest_env.PrependUnique(LIBS = [ 'libTGMSDKLibrary', - 'oc', - 'octbstack', + 'coap', + 'connectivity_abstraction', 'oc_logger', 'oc_logger_core', - 'connectivity_abstraction', - gtest, - gtest_main]) - -ThingsManager_gtest_env.AppendUnique(LIBS = ['dl']) + 'oc', + 'octbstack', + 'gtest', + 'gtest_main']) ###################################################################### # Build Test ###################################################################### -ThingsManager_gtest_src = env.Glob('./*.cpp') +ThingsManager_gtest_src = ThingsManager_gtest_env.Glob('./*.cpp') ThingsManagerTest = ThingsManager_gtest_env.Program('ThingsManagerTest', ThingsManager_gtest_src) Alias("ThingsManagerTest", ThingsManagerTest) -env.AppendTarget('ThingsManagerTest') +ThingsManager_gtest_env.AppendTarget('ThingsManagerTest') -if env.get('TEST') == '1': - target_os = env.get('TARGET_OS') - if target_os == 'linux': +if ThingsManager_gtest_env.get('TEST') == '1': + if target_os in ['linux']: from tools.scons.RunTest import * run_test(ThingsManager_gtest_env, '', - 'service/things-manager/unittests/ThingsManagerTest')
\ No newline at end of file + 'service/things-manager/unittests/ThingsManagerTest') |