--- /dev/null
+[general]
+upstream_branch = upstream
+upstream_tag = ${upstreamversion}
+
extlibs/android/sdk/android-sdk-linux
extlibs/android/sdk/android-sdk-macosx
extlibs/android/sdk/android-sdk-windows
-extlibs/boost/boost_1_58_0
+extlibs/boost/*
extlibs/tinycbor/tinycbor
*.tgz
*.zip
# Build 'resource' sub-project
SConscript(build_dir + 'resource/SConscript')
-if target_os not in ['arduino','darwin','ios', 'android']:
+if target_os not in ['arduino','darwin','ios', 'android', 'msys_nt', 'windows']:
SConscript(build_dir + 'examples/OICMiddle/SConscript')
# Build 'service' sub-project
if target_os == 'arduino':
env.UploadHelp()
-# to install the generated pc file into custome prefix location
+# to install the generated pc file into custom prefix location
env.UserInstallTargetPCFile('iotivity.pc', 'iotivity.pc')
minSdkVersion 21\r
targetSdkVersion 21\r
versionCode 1\r
- versionName "1.1"\r
+ versionName "1.1.1"\r
buildConfigField 'int', 'SECURED', SECURED\r
}\r
buildTypes {\r
JniEntityHandler.cpp \\r
JniOnResourceFoundListener.cpp \\r
JniOnDeviceInfoListener.cpp \\r
- JniOnPlatformInfoListener.cpp \\r
+ JniOnPlatformInfoListener.cpp \\r
JniOnPresenceListener.cpp \\r
JniOnGetListener.cpp \\r
JniOnPutListener.cpp \\r
JniOcPlatform.cpp \\r
JniOcResource.cpp \\r
JniOcResourceIdentifier.cpp \\r
- JniOcSecurity.cpp\r
+ JniOcSecurity.cpp \\r
+ JniOnDPDevicesFoundListener.cpp \\r
+ JniOnDirectPairingListener.cpp \\r
+ JniOcDirectPairDevice.cpp\r
ifeq ($(SECURED), 1)\r
-LOCAL_SRC_FILES += JniOcSecureResource.cpp \\r
- JniOcProvisioning.cpp \\r
- JniSecureUtils.cpp \\r
- JniProvisionResultListner.cpp \\r
- JniPinCheckListener.cpp \\r
- JniDisplayPinListener.cpp\r
-endif\r
+ LOCAL_SRC_FILES += JniOcSecureResource.cpp \\r
+ JniOcProvisioning.cpp \\r
+ JniSecureUtils.cpp \\r
+ JniProvisionResultListner.cpp \\r
+ JniPinCheckListener.cpp \\r
+ JniDisplayPinListener.cpp\r
+ endif\r
\r
LOCAL_LDLIBS := -llog\r
LOCAL_STATIC_LIBRARIES := android-oc\r
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
(void)clazz;
CAUtilCreateBond(env, device);
}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_setLeScanIntervalTimeImpl(JNIEnv *env, jclass clazz,
+ jint intervalTime, jint workignCount)
+{
+ LOGI("setLeScanIntervalTimeImpl");
+ (void)env;
+ (void)clazz;
+ CAUtilSetLEScanInterval(intervalTime, workignCount);
+}
+
JNIEXPORT void JNICALL Java_org_iotivity_ca_CaInterface_initialize
(JNIEnv *, jclass, jobject, jobject);
+ /*
+ * Class: Java_org_iotivity_ca_CaInterface_setLeScanIntervalTimeImpl
+ * Method: setLeScanIntervalTimeImpl
+ * Signature: (II)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_ca_CaInterface_setLeScanIntervalTimeImpl
+ (JNIEnv *, jclass, jint, jint);
+
#ifdef __cplusplus
}
#endif
LOGI("~JniDisplayPinListener()");
if (m_jgListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
if (NULL == env) return;
env->DeleteGlobalRef(m_jgListener);
void JniDisplayPinListener::displayPinCallback(char *pinBuf, size_t pinSize)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (NULL == env) return;
+ if (NULL == env)
+ {
+ return;
+ }
jclass clsL = env->GetObjectClass(m_jgListener);
LOGD("~JniEntityHandler");
if (m_jListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
if (nullptr == env)
{
const std::shared_ptr<OCResourceRequest> request)
{
LOGD("JniEntityHandler_handleEntity");
- jint envRet;
+ jint envRet = JNI_ERR;
JNIEnv *env = GetJNIEnv(envRet);
if (nullptr == env)
{
jmethodID getValue_ID = env->GetMethodID(clsResult, "getValue", "()I");
if (!getValue_ID)
{
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return OC_EH_ERROR;
}
jint jResult = env->CallIntMethod(entityHandlerResult, getValue_ID);
break;
}
}
+
if (!onEventListener)
{
onEventListener = new T(env, jListener, owner);
{
LOGD("OnEventListener: Failed to create global listener ref.");
delete onEventListener;
+ return nullptr;
}
LOGD("OnEventListener: new listener");
}
+
m_mapMutex.unlock();
return onEventListener;
}
--- /dev/null
+/*
+* //******************************************************************
+* //
+* // 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);
+}
--- /dev/null
+/*
+* //******************************************************************
+* //
+* // 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
+
#include "JniOcPresenceHandle.h"
#include "JniOcResourceResponse.h"
#include "JniOcSecurity.h"
+#include "JniOcDirectPairDevice.h"
#include "JniUtils.h"
+#include "ocpayload.h"
using namespace OC;
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
JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(
env, jResourceHandle);
- if (!jniOcResourceHandle) return;
+ if (!jniOcResourceHandle)
+ {
+ return;
+ }
try
{
return;
}
- try{
+ try {
OCStackResult result = OCPlatform::notifyAllObservers(
jniOcResourceHandle->getOCResourceHandle(),
JniUtils::getQOS(env, static_cast<int>(jQoS)));
}
/*
+ * 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
return nullptr;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, jResource);
- if (!resource) return nullptr;
+ if (!resource)
+ {
+ return nullptr;
+ }
OCResourceHandle resourceHandle;
try
JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_registerDeviceInfo0(
JNIEnv *env,
jclass clazz,
- jstring jDeviceName)
+ jstring jDeviceName,
+ jobjectArray jDeviceTypes)
{
LOGI("OcPlatform_registerDeviceInfo");
- std::string deviceName;
- if (jDeviceName)
+ if (!jDeviceName)
+ {
+ ThrowOcException(OC_STACK_INVALID_PARAM, "deviceName cannot be null");
+ return;
+ }
+
+ if (!jDeviceTypes)
{
- deviceName = env->GetStringUTFChars(jDeviceName, nullptr);
+ ThrowOcException(OC_STACK_INVALID_PARAM, "deviceTypes cannot be null");
+ return;
}
OCDeviceInfo deviceInfo;
try
{
- DuplicateString(&deviceInfo.deviceName, deviceName);
+ DuplicateString(&deviceInfo.deviceName, env->GetStringUTFChars(jDeviceName, nullptr));
+ deviceInfo.types = NULL;
+
+ jsize len = env->GetArrayLength(jDeviceTypes);
+ for (jsize i = 0; i < len; ++i)
+ {
+ jstring jStr = (jstring)env->GetObjectArrayElement(jDeviceTypes, i);
+ if (!jStr)
+ {
+ delete deviceInfo.deviceName;
+ ThrowOcException(OC_STACK_INVALID_PARAM, "device type cannot be null");
+ return;
+ }
+
+ OCResourcePayloadAddStringLL(&deviceInfo.types, env->GetStringUTFChars(jStr, nullptr));
+ if (env->ExceptionCheck())
+ {
+ delete deviceInfo.deviceName;
+ return;
+ }
+
+ env->DeleteLocalRef(jStr);
+ }
}
catch (std::exception &e)
{
}
JniOcResourceHandle* jniOcResourceCollectionHandle =
JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceCollectionHandle);
- if (!jniOcResourceCollectionHandle) return;
+ if (!jniOcResourceCollectionHandle)
+ {
+ return;
+ }
JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(
env, jResourceHandle);
JniOcResourceHandle* jniOcResourceHandle =
JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceHandle);
- if (!jniOcResourceHandle) return;
+ if (!jniOcResourceHandle)
+ {
+ return;
+ }
try
{
JniOcResourceResponse *jniResponse =
JniOcResourceResponse::getJniOcResourceResponsePtr(env, jResourceResponse);
- if (!jniResponse) return;
+ if (!jniResponse)
+ {
+ return;
+ }
try
{
#include "JniOnResourceFoundListener.h"
#include "JniOnDeviceInfoListener.h"
#include "JniOnPlatformInfoListener.h"
+#include "JniOnDPDevicesFoundListener.h"
+#include "JniOnDirectPairingListener.h"
#include "JniOnPresenceListener.h"
#include <mutex>
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" {
/*
* 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
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
JniOcPresenceHandle::JniOcPresenceHandle(JniOnPresenceListener* jniListener, OCPresenceHandle presenceHandle)
: m_jniListener(jniListener), m_presenceHandle(presenceHandle)
-{}
+{
+}
JniOcPresenceHandle::~JniOcPresenceHandle()
{
LOGD("OcPresenceHandle_dispose");
JniOcPresenceHandle *presenceHandle = JniOcPresenceHandle::getJniOcPresenceHandlePtr(env, thiz);
delete presenceHandle;
-}
\ No newline at end of file
+}
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
+
+#include <map>
+
#include "JniOcRepresentation.h"
#include "JniUtils.h"
/*
* Class: org_iotivity_base_OcRepresentation
+* Method: getValues
+* Signature: ()Ljava/util/Map;
+*/
+JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getValues
+(JNIEnv *env, jobject thiz)
+{
+ LOGD("OcRepresentation_getValues");
+ OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
+ if (!rep)
+ {
+ return nullptr;
+ }
+
+ std::map<std::string, AttributeValue> values = rep->getValues();
+ jobject jHashMap = env->NewObject(g_cls_HashMap, g_mid_HashMap_ctor);
+ if (!jHashMap)
+ {
+ return nullptr;
+ }
+
+ for (std::map<std::string, AttributeValue>::const_iterator it = values.begin(); it != values.end(); it++)
+ {
+ jobject key = static_cast<jobject>(env->NewStringUTF(it->first.c_str()));
+ jobject val = boost::apply_visitor(JObjectConverter(env), it->second);
+ env->CallObjectMethod(jHashMap, g_mid_HashMap_put, key, val);
+ }
+ return jHashMap;
+}
+
+/*
+* Class: org_iotivity_base_OcRepresentation
* Method: getValueN
* Signature: (Ljava/lang/String;)Ljava/lang/Object;
*/
return nullptr;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return nullptr;
+ if (!rep)
+ {
+ return nullptr;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string str = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(str, static_cast<int>(jValue));
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string str = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(str, static_cast<double>(jValue));
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string str = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(str, static_cast<bool>(jValue));
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
std::string value = env->GetStringUTFChars(jValue, nullptr);
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
if (jValue)
{
OCRepresentation *value = JniOcRepresentation::getOCRepresentationPtr(env, jValue);
- if (!value) return;
+ if (!value)
+ {
+ return;
+ }
rep->setValue(key, *value);
}
else
env->ReleaseIntArrayElements(jValue, ints, JNI_ABORT);
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
env->ReleaseDoubleArrayElements(jValue, doubles, JNI_ABORT);
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
env->ReleaseBooleanArrayElements(jValue, booleans, JNI_ABORT);
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
JniUtils::convertJavaStrArrToStrVector(env, jValue, value);
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
-
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
JniUtils::convertJavaRepresentationArrToVector(env, jValue, value);
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
env->ReleaseByteArrayElements(jValue, bytes, JNI_ABORT);
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
{
LOGD("OcRepresentation_addChild");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
OCRepresentation *child = JniOcRepresentation::getOCRepresentationPtr(env, jOcRepresentation);
- if (!child) return;
+ if (!child)
+ {
+ return;
+ }
rep->addChild(*child);
}
{
LOGD("OcRepresentation_clearChildren");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
rep->clearChildren();
}
{
LOGD("OcRepresentation_getChildrenArray");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return nullptr;
+ if (!rep)
+ {
+ return nullptr;
+ }
return JniUtils::convertRepresentationVectorToJavaArray(env, rep->getChildren());
}
{
LOGD("OcRepresentation_getUri");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return nullptr;
+ if (!rep)
+ {
+ return nullptr;
+ }
std::string uri(rep->getUri());
return env->NewStringUTF(uri.c_str());
{
LOGD("OcRepresentation_getHost");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return nullptr;
+ if (!rep)
+ {
+ return nullptr;
+ }
std::string uri(rep->getHost());
return env->NewStringUTF(uri.c_str());
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
rep->setUri(env->GetStringUTFChars(jUri, nullptr));
}
return false;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return false;
+ if (!rep)
+ {
+ return false;
+ }
std::string str = env->GetStringUTFChars(jstr, nullptr);
return rep->hasAttribute(str);
{
LOGD("OcRepresentation_getResourceTypes");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return nullptr;
+ if (!rep)
+ {
+ return nullptr;
+ }
std::vector<std::string> resourceTypes = rep->getResourceTypes();
return JniUtils::convertStrVectorToJavaStrList(env, resourceTypes);
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::vector<std::string> resourceTypes;
JniUtils::convertJavaStrArrToStrVector(env, jResourceTypeArray, resourceTypes);
{
LOGD("OcRepresentation_getResourceInterfaces");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return nullptr;
+ if (!rep)
+ {
+ return nullptr;
+ }
std::vector<std::string> resourceInterfaces = rep->getResourceInterfaces();
return JniUtils::convertStrVectorToJavaStrList(env, resourceInterfaces);
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::vector<std::string> resourceInterfaces;
JniUtils::convertJavaStrArrToStrVector(env, jResourceInterfaceArray, resourceInterfaces);
{
LOGD("OcRepresentation_isEmpty");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return false;
+ if (!rep)
+ {
+ return false;
+ }
return static_cast<jboolean>(rep->empty());
}
{
LOGD("OcRepresentation_size");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return -1;
+ if (!rep)
+ {
+ return -1;
+ }
return static_cast<jint>(rep->numberOfAttributes());
}
return false;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return false;
+ if (!rep)
+ {
+ return false;
+ }
std::string attributeKey = env->GetStringUTFChars(jAttributeKey, nullptr);
return static_cast<jboolean>(rep->erase(attributeKey));
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string attributeKey = env->GetStringUTFChars(jAttributeKey, nullptr);
rep->setNULL(attributeKey);
return false;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return false;
+ if (!rep)
+ {
+ return false;
+ }
std::string attributeKey = env->GetStringUTFChars(jAttributeKey, nullptr);
return static_cast<jboolean>(rep->isNULL(attributeKey));
struct JObjectConverter : boost::static_visitor < jobject >
{
- JObjectConverter(JNIEnv *env) : env(env){}
+ JObjectConverter(JNIEnv *env) : env(env)
+ {
+ }
+
+ jobject operator()(const NullType&) const
+ {
+ return nullptr;
+ }
- jobject operator()(const NullType&) const { return nullptr; }
jobject operator()(const int& val) const
{
jobject jobj = env->NewObject(
{
size_t len = val.size();
jintArray jIntArray = env->NewIntArray(len);
- if (!jIntArray) return nullptr;
+ if (!jIntArray)
+ {
+ return nullptr;
+ }
const int* ints = &val[0];
env->SetIntArrayRegion(jIntArray, 0, len, reinterpret_cast<const jint*>(ints));
return jIntArray;
{
size_t len = val.size();
jdoubleArray jDoubleArray = env->NewDoubleArray(len);
- if (!jDoubleArray) return nullptr;
+ if (!jDoubleArray)
+ {
+ return nullptr;
+ }
const double* doubles = &val[0];
env->SetDoubleArrayRegion(jDoubleArray, 0, len, reinterpret_cast<const jdouble*>(doubles));
return jDoubleArray;
{
size_t len = val.size();
jbooleanArray jBooleanArray = env->NewBooleanArray(len);
- if (!jBooleanArray) return nullptr;
+ if (!jBooleanArray)
+ {
+ return nullptr;
+ }
jboolean* booleans = new jboolean[len];
- for (size_t i = 0; i < len; ++i) {
+ for (size_t i = 0; i < len; ++i)
+ {
booleans[i] = static_cast<jboolean>(val[i]);
}
env->SetBooleanArrayRegion(jBooleanArray, 0, len, booleans);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->ReleaseBooleanArrayElements(jBooleanArray, booleans, 0);
return jBooleanArray;
}
{
size_t len = val.size();
jobjectArray strArr = env->NewObjectArray(len, g_cls_String, nullptr);
- if (!strArr) return nullptr;
+ if (!strArr)
+ {
+ return nullptr;
+ }
for (size_t i = 0; i < len; ++i)
{
jstring jString = env->NewStringUTF(val[i].c_str());
env->SetObjectArrayElement(strArr, static_cast<jsize>(i), jString);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jString);
}
return strArr;
{
jsize len = static_cast<jsize>(val.size());
jobjectArray repArr = env->NewObjectArray(len, g_cls_OcRepresentation, nullptr);
- if (!repArr) return nullptr;
+ if (!repArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < len; ++i)
{
OCRepresentation* rep = new OCRepresentation(val[i]);
{
size_t len = val.size();
jbyteArray jByteArray = env->NewByteArray(len);
- if (!jByteArray) return nullptr;
+ if (!jByteArray)
+ {
+ return nullptr;
+ }
const uint8_t* bytes = &val[0];
env->SetByteArrayRegion(jByteArray, 0, len, reinterpret_cast<const jbyte*>(bytes));
return jByteArray;
{
size_t lenInner = val[i].size();
jintArray jIntArray = env->NewIntArray(lenInner);
- if (!jIntArray) return nullptr;
+ if (!jIntArray)
+ {
+ return nullptr;
+ }
const int* ints = &val[i][0];
env->SetIntArrayRegion(jIntArray, 0, lenInner, reinterpret_cast<const jint*>(ints));
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->SetObjectArrayElement(jOuterArr, i, static_cast<jobject>(jIntArray));
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jIntArray);
}
return jOuterArr;
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_int2DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
+
for (jsize k = 0; k < lenOuter; ++k)
{
jsize lenMiddle = static_cast<jsize>(val[k].size());
jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_int1DArray, nullptr);
- if (!jMiddleArr) return nullptr;
+ if (!jMiddleArr)
+ {
+ return nullptr;
+ }
+
for (jsize i = 0; i < lenMiddle; ++i)
{
jsize lenInner = static_cast<jsize>(val[k][i].size());
jintArray jIntArray = env->NewIntArray(lenInner);
- if (!jIntArray) return nullptr;
+ if (!jIntArray)
+ {
+ return nullptr;
+ }
const int* ints = &val[k][i][0];
env->SetIntArrayRegion(jIntArray, 0, lenInner, reinterpret_cast<const jint*>(ints));
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->SetObjectArrayElement(jMiddleArr, i, jIntArray);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jIntArray);
}
env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jMiddleArr);
}
return jOuterArr;
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_double1DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
+
for (jsize i = 0; i < lenOuter; ++i)
{
size_t lenInner = val[i].size();
jdoubleArray jDoubleArray = env->NewDoubleArray(lenInner);
- if (!jDoubleArray) return nullptr;
+ if (!jDoubleArray)
+ {
+ return nullptr;
+ }
+
const double* doubles = &val[i][0];
env->SetDoubleArrayRegion(jDoubleArray, 0, lenInner, reinterpret_cast<const jdouble*>(doubles));
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->SetObjectArrayElement(jOuterArr, i, jDoubleArray);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jDoubleArray);
}
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_double2DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
for (jsize k = 0; k < lenOuter; ++k)
{
jsize lenMiddle = static_cast<jsize>(val[k].size());
jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_double1DArray, nullptr);
- if (!jMiddleArr) return nullptr;
+ if (!jMiddleArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < lenMiddle; ++i)
{
jsize lenInner = static_cast<jsize>(val[k][i].size());
jdoubleArray jDoubleArray = env->NewDoubleArray(lenInner);
- if (!jDoubleArray) return nullptr;
+ if (!jDoubleArray)
+ {
+ return nullptr;
+ }
const double* doubles = &val[k][i][0];
env->SetDoubleArrayRegion(jDoubleArray, 0, lenInner, reinterpret_cast<const jdouble*>(doubles));
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->SetObjectArrayElement(jMiddleArr, i, jDoubleArray);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jDoubleArray);
}
env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jMiddleArr);
}
return jOuterArr;
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_boolean1DArray, 0);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < lenOuter; ++i)
{
size_t lenInner = val[i].size();
jbooleanArray jBooleanArray = env->NewBooleanArray(lenInner);
- if (!jBooleanArray) return nullptr;
+ if (!jBooleanArray)
+ {
+ return nullptr;
+ }
jboolean* booleans = new jboolean[lenInner];
- for (size_t j = 0; j < lenInner; ++j) {
+ for (size_t j = 0; j < lenInner; ++j)
+ {
booleans[j] = static_cast<jboolean>(val[i][j]);
}
env->SetBooleanArrayRegion(jBooleanArray, 0, lenInner, booleans);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->SetObjectArrayElement(jOuterArr, i, jBooleanArray);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->ReleaseBooleanArrayElements(jBooleanArray, booleans, 0);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jBooleanArray);
}
return jOuterArr;
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_boolean2DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
for (jsize k = 0; k < lenOuter; ++k)
{
jsize lenMiddle = static_cast<jsize>(val[k].size());
jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_boolean1DArray, nullptr);
- if (!jMiddleArr) return nullptr;
+ if (!jMiddleArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < lenMiddle; ++i)
{
size_t lenInner = val[k][i].size();
jbooleanArray jBooleanArray = env->NewBooleanArray(lenInner);
jboolean* booleans = new jboolean[lenInner];
- for (size_t j = 0; j < lenInner; ++j) {
+ for (size_t j = 0; j < lenInner; ++j)
+ {
booleans[j] = val[k][i][j];
}
env->SetBooleanArrayRegion(jBooleanArray, 0, lenInner, booleans);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->SetObjectArrayElement(jMiddleArr, i, jBooleanArray);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->ReleaseBooleanArrayElements(jBooleanArray, booleans, 0);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jBooleanArray);
}
env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
- if (env->ExceptionCheck()) return nullptr;
- env->DeleteLocalRef(jMiddleArr);
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ } env->DeleteLocalRef(jMiddleArr);
}
return jOuterArr;
}
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_String1DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < lenOuter; ++i)
{
jsize lenInner = static_cast<jsize>(val[i].size());
jobjectArray strArr = env->NewObjectArray(lenInner, g_cls_String, nullptr);
- if (!strArr) return nullptr;
+ if (!strArr)
+ {
+ return nullptr;
+ }
for (jsize j = 0; j < lenInner; ++j)
{
jstring jString = env->NewStringUTF(val[i][j].c_str());
env->SetObjectArrayElement(strArr, j, jString);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jString);
}
env->SetObjectArrayElement(jOuterArr, i, strArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(strArr);
}
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_String2DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
for (jsize k = 0; k < lenOuter; ++k)
{
jsize lenMiddle = static_cast<jsize>(val[k].size());
jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_String1DArray, nullptr);
- if (!jMiddleArr) return nullptr;
+ if (!jMiddleArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < lenMiddle; ++i)
{
jsize lenInner = static_cast<jsize>(val[k][i].size());
jobjectArray strArr = env->NewObjectArray(lenInner, g_cls_String, nullptr);
- if (!strArr) return nullptr;
+ if (!strArr)
+ {
+ return nullptr;
+ }
for (jsize j = 0; j < lenInner; ++j)
{
jstring jString = env->NewStringUTF(val[k][i][j].c_str());
env->SetObjectArrayElement(strArr, j, jString);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jString);
}
env->SetObjectArrayElement(jMiddleArr, i, strArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(strArr);
}
env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jMiddleArr);
}
return jOuterArr;
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_OcRepresentation1DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < lenOuter; ++i)
{
jsize lenInner = static_cast<jsize>(val[i].size());
jobjectArray repArr = env->NewObjectArray(lenInner, g_cls_OcRepresentation, nullptr);
- if (!repArr) return nullptr;
+ if (!repArr)
+ {
+ return nullptr;
+ }
for (jsize j = 0; j < lenInner; ++j)
{
OCRepresentation* rep = new OCRepresentation(val[i][j]);
return nullptr;
}
env->SetObjectArrayElement(repArr, j, jRepresentation);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jRepresentation);
}
env->SetObjectArrayElement(jOuterArr, i, repArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(repArr);
}
return jOuterArr;
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_OcRepresentation2DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
for (jsize k = 0; k < lenOuter; ++k)
{
jsize lenMiddle = static_cast<jsize>(val[k].size());
jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_OcRepresentation1DArray, nullptr);
- if (!jMiddleArr) return nullptr;
+ if (!jMiddleArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < lenMiddle; ++i)
{
jsize lenInner = static_cast<jsize>(val[k][i].size());
jobjectArray repArr = env->NewObjectArray(lenInner, g_cls_OcRepresentation, nullptr);
- if (!repArr) return nullptr;
+ if (!repArr)
+ {
+ return nullptr;
+ }
for (jsize j = 0; j < lenInner; ++j)
{
OCRepresentation* rep = new OCRepresentation(val[k][i][j]);
return nullptr;
}
env->SetObjectArrayElement(repArr, j, jRepresentation);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jRepresentation);
}
env->SetObjectArrayElement(jMiddleArr, i, repArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(repArr);
}
env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jMiddleArr);
}
return jOuterArr;
/*
* Class: org_iotivity_base_OcRepresentation
+ * Method: getValues
+ * Signature: ()Ljava/util/Map;
+ */
+ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getValues
+ (JNIEnv *, jobject);
+
+ /*
+ * Class: org_iotivity_base_OcRepresentation
* Method: getValueN
* Signature: (Ljava/lang/String;)Ljava/lang/Object;
*/
#include "JniOcRequestHandle.h"
JniOcRequestHandle::JniOcRequestHandle(OCRequestHandle requestHandle) : m_requestHandle(requestHandle)
-{}
+{
+}
JniOcRequestHandle::~JniOcRequestHandle()
{
LOGD("OcRequestHandle_dispose");
JniOcRequestHandle *handle = JniOcRequestHandle::getJniOcRequestHandlePtr(env, thiz);
delete handle;
-}
\ No newline at end of file
+}
JniOcResource::JniOcResource(std::shared_ptr<OCResource> resource)
: m_sharedResource(resource)
-{}
+{
+}
JniOcResource::~JniOcResource()
{
m_sharedResource = nullptr;
- jint envRet;
+ jint envRet = JNI_ERR;
JNIEnv *env = GetJNIEnv(envRet);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
m_onGetManager.removeAllListeners(env);
m_onPutManager.removeAllListeners(env);
m_onDeleteManager.removeAllListeners(env);
m_onObserveManager.removeAllListeners(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
OCStackResult JniOcResource::get(JNIEnv* env, const QueryParamsMap &queryParametersMap, jobject jListener)
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
resourceInterface = env->GetStringUTFChars(jResourceInterface, nullptr);
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
try
{
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
try
{
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
{
LOGD("OcResource_cancelObserve1");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
try
{
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
HeaderOptions headerOptions;
JniUtils::convertJavaHeaderOptionsArrToVector(env, jheaderOptionArr, headerOptions);
{
LOGD("OcResource_unsetHeaderOptions");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
resource->unsetHeaderOptions();
}
{
LOGD("OcResource_getHost");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return nullptr;
+ if (!resource)
+ {
+ return nullptr;
+ }
return env->NewStringUTF(resource->host().c_str());
}
{
LOGD("OcResource_getUri");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return nullptr;
+ if (!resource)
+ {
+ return nullptr;
+ }
return env->NewStringUTF(resource->uri().c_str());
}
{
LOGD("OcResource_getConnectivityType");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return -1;
+ if (!resource)
+ {
+ return -1;
+ }
OCConnectivityType connectivityType = resource->connectivityType();
return static_cast<jint>(connectivityType);
{
LOGD("OcResource_isObservable");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
+ if (!resource)
+ {
+ return false;
+ }
+
return (jboolean)resource->isObservable();
}
{
LOGD("OcResource_getResourceTypes");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return nullptr;
+ if (!resource)
+ {
+ return nullptr;
+ }
std::vector<std::string> resourceTypes = resource->getResourceTypes();
{
LOGD("OcResource_getResourceInterfaces");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return nullptr;
+ if (!resource)
+ {
+ return nullptr;
+ }
std::vector<std::string> resourceInterfaces = resource->getResourceInterfaces();
{
LOGD("OcResource_getUniqueIdentifier");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return nullptr;
+ if (!resource)
+ {
+ return nullptr;
+ }
JniOcResourceIdentifier *jniResourceIdentifier =
new JniOcResourceIdentifier(resource->uniqueIdentifier());
- if (!jniResourceIdentifier) return nullptr;
+ if (!jniResourceIdentifier)
+ {
+ return nullptr;
+ }
jlong handle = reinterpret_cast<jlong>(jniResourceIdentifier);
jobject jResourceIdentifier = env->NewObject(g_cls_OcResourceIdentifier,
{
LOGD("OcResource_getServerId");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return nullptr;
+ if (!resource)
+ {
+ return nullptr;
+ }
return env->NewStringUTF(resource->sid().c_str());
}
LOGD("OcResource_dispose");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
delete resource;
-}
\ No newline at end of file
+}
JniOcResourceHandle::JniOcResourceHandle(OCResourceHandle resourceHandle)
: m_resourceHandle(resourceHandle)
-{}
+{
+}
JniOcResourceHandle::~JniOcResourceHandle()
{
LOGD("OcResourceHandle_dispose");
JniOcResourceHandle *resourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env, thiz);
delete resourceHandle;
-}
\ No newline at end of file
+}
JniOcResourceIdentifier::JniOcResourceIdentifier(OC::OCResourceIdentifier resourceIdentifier)
: m_resourceIdentifier(resourceIdentifier)
-{}
+{
+}
JniOcResourceIdentifier::~JniOcResourceIdentifier()
{
(JNIEnv *env, jobject jThiz, jobject jOther)
{
JniOcResourceIdentifier *thiz = JniOcResourceIdentifier::getJniOcResourceIdentifierPtr(env, jThiz);
- if (!thiz) return false;
+ if (!thiz)
+ {
+ return false;
+ }
JniOcResourceIdentifier *other = JniOcResourceIdentifier::getJniOcResourceIdentifierPtr(env, jOther);
- if (!other) return false;
+ if (!other)
+ {
+ return false;
+ }
if (thiz->getOCResourceIdentifier() == other->getOCResourceIdentifier())
{
LOGD("JniOcResourceIdentifier_dispose");
JniOcResourceIdentifier *identifier = JniOcResourceIdentifier::getJniOcResourceIdentifierPtr(env, thiz);
delete identifier;
-}
\ No newline at end of file
+}
JniOcResourceRequest::JniOcResourceRequest(const std::shared_ptr<OCResourceRequest> request)
: m_request(request)
-{}
+{
+}
JniOcResourceRequest::~JniOcResourceRequest()
-{}
+{
+}
std::string
JniOcResourceRequest::getRequestType()
{
LOGD("OcResourceRequest_getRequestTypeNative");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
-
+ if (!request)
+ {
+ return nullptr;
+ }
std::string requestType = request->getRequestType();
return env->NewStringUTF(requestType.c_str());
}
{
LOGD("OcResourceRequest_getQueryParameters");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
+ if (!request)
+ {
+ return nullptr;
+ }
return JniUtils::convertQueryParamsMapToJavaMap(env, request->getQueryParameters());
}
{
LOGD("OcResourceRequest_getRequestHandlerFlagNative");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return -1;
+ if (!request)
+ {
+ return -1;
+ }
return static_cast<jint>(request->getRequestHandlerFlag());
}
{
LOGD("OcResourceRequest_getResourceRepresentation");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
+ if (!request)
+ {
+ return nullptr;
+ }
OCRepresentation *ocRepresentation = new OCRepresentation(request->getResourceRepresentation());
- if (!ocRepresentation) return nullptr;
+ if (!ocRepresentation)
+ {
+ return nullptr;
+ }
jlong handle = reinterpret_cast<jlong>(ocRepresentation);
jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,
{
LOGD("OcResourceRequest_getObservationInfo");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
-
+ if (!request)
+ {
+ return nullptr;
+ }
ObservationInfo oInfo = request->getObservationInfo();
jobject jObservationInfo = env->NewObject(g_cls_ObservationInfo, g_mid_ObservationInfo_N_ctor,
return;
}
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return;
-
+ if (!request)
+ {
+ return;
+ }
request->setResourceUri(env->GetStringUTFChars(jUri, 0));
}
{
LOGD("OcResourceRequest_getResourceUri");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
-
+ if (!request)
+ {
+ return nullptr;
+ }
std::string requestUri = request->getResourceUri();
return env->NewStringUTF(requestUri.c_str());
}
{
LOGD("OcResourceRequest_getHeaderOptions");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
-
+ if (!request)
+ {
+ return nullptr;
+ }
return JniUtils::convertHeaderOptionsVectorToJavaList(env, request->getHeaderOptions());
}
{
LOGD("OcResourceRequest_getRequestHandle");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
+ if (!request)
+ {
+ return nullptr;
+ }
JniOcRequestHandle* jniHandle = new JniOcRequestHandle(request->getRequestHandle());
jlong handle = reinterpret_cast<jlong>(jniHandle);
{
LOGD("OcResourceRequest_getResourceHandle");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
+ if (!request)
+ {
+ return nullptr;
+ }
JniOcResourceHandle* jniHandle = new JniOcResourceHandle(
request->getResourceHandle());
LOGD("OcResourceRequest_dispose");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
delete request;
-}
\ No newline at end of file
+}
JniOcResourceResponse::JniOcResourceResponse
(std::shared_ptr<OCResourceResponse> resourceResponse)
-: m_response(resourceResponse){}
+: m_response(resourceResponse)
+{
+}
JniOcResourceResponse::~JniOcResourceResponse()
-{}
+{
+}
void JniOcResourceResponse::setErrorCode(const int eCode)
{
{
LOGD("OcResourceResponse_setErrorCode");
JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!response) return;
-
+ if (!response)
+ {
+ return;
+ }
response->setErrorCode(static_cast<int>(eCode));
}
{
LOGD("OcResourceResponse_getNewResourceUri");
JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!response) return nullptr;
-
+ if (!response)
+ {
+ return nullptr;
+ }
return env->NewStringUTF(response->getNewResourceUri().c_str());
}
{
LOGD("OcResourceResponse_setNewResourceUri");
JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!response) return;
-
+ if (!response)
+ {
+ return;
+ }
response->setNewResourceUri(env->GetStringUTFChars(jstr, 0));
}
return;
}
JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!jniResponse) return;
-
+ if (!jniResponse)
+ {
+ return;
+ }
HeaderOptions headerOptions;
JniUtils::convertJavaHeaderOptionsArrToVector(env, jHeaderOptions, headerOptions);
return;
}
JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!jniResponse) return;
-
+ if (!jniResponse)
+ {
+ return;
+ }
JniOcRequestHandle* jniOcRequestHandle = JniOcRequestHandle::getJniOcRequestHandlePtr(env, jRequestHandle);
- if (!jniOcRequestHandle) return;
-
+ if (!jniOcRequestHandle)
+ {
+ return;
+ }
jniResponse->setRequestHandle(jniOcRequestHandle->getOCRequestHandle());
}
return;
}
JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!jniResponse) return;
-
+ if (!jniResponse)
+ {
+ return;
+ }
JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceHandle);
- if (!jniOcResourceHandle) return;
-
+ if (!jniOcResourceHandle)
+ {
+ return;
+ }
jniResponse->setResourceHandle(jniOcResourceHandle->getOCResourceHandle());
}
{
LOGD("OcResourceResponse_setResponseResult");
JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!response) return;
-
+ if (!response)
+ {
+ return;
+ }
response->setResponseResult(JniUtils::getOCEntityHandlerResult(env, static_cast<int>(responseResult)));
}
JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env,
thiz);
- if (!response) return;
-
+ if (!response)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env,
jRepresentation);
- if (!representation) return;
-
+ if (!representation)
+ {
+ return;
+ }
response->setResourceRepresentation(*representation, env->GetStringUTFChars(jstr, 0));
}
return;
}
JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!response) return;
-
+ if (!response)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env,
jRepresentation);
LOGD("OcResourceResponse_dispose");
JniOcResourceResponse *resp = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
delete resp;
-}
\ No newline at end of file
+}
#include "JniOcSecureResource.h"
#include "JniSecureUtils.h"
+#include "oic_string.h"
namespace PH = std::placeholders;
JniOcSecureResource::JniOcSecureResource(std::shared_ptr<OCSecureResource> device)
: m_sharedSecureResource(device)
-{}
+{
+}
JniOcSecureResource::~JniOcSecureResource()
{
return ret;
}
+OCStackResult JniOcSecureResource::provisionDirectPairing(JNIEnv* env, jobjectArray jpdacls,
+ jobject jListener, std::string pin, std::vector<int> prms, int edp)
+{
+ OCStackResult ret;
+ JniProvisionResultListner *resultListener = AddProvisionResultListener(env, jListener);
+
+ jsize len = env->GetArrayLength(jpdacls);
+
+ OicSecPconf_t *pconf = nullptr;
+ OicSecPdAcl_t *head = nullptr;
+
+ for (jsize i = 0; i < len; ++i)
+ {
+ OicSecPdAcl_t *pdacl = new OicSecPdAcl_t;
+ if (!pdacl)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ memset(pdacl, 0, sizeof(OicSecPdAcl_t));
+ pdacl->next = nullptr;
+
+ jobject jpdacl = env->GetObjectArrayElement(jpdacls, i);
+
+ if (OC_STACK_OK != JniSecureUtils::convertJavaPdACLToOCAcl(env, jpdacl, pdacl))
+ {
+ delete pdacl;
+ return OC_STACK_ERROR;
+ }
+
+ pdacl->next = head;
+ head = pdacl;
+ }
+
+ pconf = new OicSecPconf_t;
+ memset(pconf, 0, sizeof(OicSecPconf_t));
+ pconf->edp = edp;
+ pconf->prmLen = prms.size();
+ pconf->prm = new OicSecPrm_t[pconf->prmLen];
+ pconf->pddevLen = 0;
+
+ for (int i = 0 ; i < prms.size(); i++)
+ pconf->prm[i] = (OicSecPrm_t)prms[i];
+
+ memcpy(pconf->pin.val, pin.c_str(), DP_PIN_LENGTH);
+ pconf->pdacls = head;
+
+ ResultCallBack resultCallback = [head, resultListener, pconf, prms]
+ (PMResultList_t *result, int hasError)
+ {
+ OicSecPdAcl_t *tmp1, *tmp2;
+ tmp1 = head;
+ while (tmp1)
+ {
+ tmp2 = tmp1->next;
+ delete tmp1;
+ tmp1 = tmp2;
+ }
+
+ delete pconf->prm;
+ delete pconf;
+ resultListener->ProvisionResultCallback(result, hasError, ListenerFunc::PROVISIONDIRECTPAIRING);
+ };
+
+ ret = m_sharedSecureResource->provisionDirectPairing(pconf, resultCallback);
+
+ if (ret != OC_STACK_OK)
+ {
+ OicSecPdAcl_t *tmp1, *tmp2;
+ tmp1 = head;
+ while (tmp1)
+ {
+ tmp2 = tmp1->next;
+ delete tmp1;
+ tmp1 = tmp2;
+ }
+
+ delete pconf->prm;
+ delete pconf;
+ }
+ return ret;
+}
+
OCStackResult JniOcSecureResource::provisionPairwiseDevices(JNIEnv* env, jint type, jint keySize,
jobject _acl1, jobject _device2, jobject _acl2, jobject jListener)
{
/*
* 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;
*/
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;
/*
* 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;
*/
#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;
jclass g_cls_OcProvisionResult = nullptr;
jclass g_cls_OcSecureResource = nullptr;
jclass g_cls_OcOicSecAcl = nullptr;
+jclass g_cls_OcOicSecPdAcl = nullptr;
+jclass g_cls_OcDirectPairDevice = nullptr;
jmethodID g_mid_Integer_ctor = nullptr;
jmethodID g_mid_Double_ctor = nullptr;
jmethodID g_mid_OcResourceIdentifier_N_ctor = nullptr;
jmethodID g_mid_OcProvisionResult_ctor = nullptr;
jmethodID g_mid_OcSecureResource_ctor = nullptr;
+jmethodID g_mid_OcDirectPairDevice_ctor = nullptr;
+jmethodID g_mid_OcDirectPairDevice_dev_ctor = nullptr;
jmethodID g_mid_OcOicSecAcl_get_subject = nullptr;
jmethodID g_mid_OcOicSecAcl_get_resources_cnt = nullptr;
jmethodID g_mid_OcOicSecAcl_get_periods = nullptr;
jmethodID g_mid_OcOicSecAcl_get_recurrences = nullptr;
jmethodID g_mid_OcOicSecAcl_get_rownerID = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_resources_cnt = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_resources = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_permission = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_periods_cnt = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_periods = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_recurrences = nullptr;
jobject getOcException(JNIEnv* env, const char* file, const char* functionName,
const int line, const int code, const char* message)
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)
LOGE("Failed to get the environment using GetEnv()");
return JNI_ERR;
}
+ VERIFY_VARIABLE_NULL(env);
jclass clazz = nullptr;
//Integer
clazz = env->FindClass("java/lang/Integer");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
+
g_cls_Integer = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_Integer_ctor = env->GetMethodID(g_cls_Integer, "<init>", "(I)V");
- if (!g_mid_Integer_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_Integer_ctor);
clazz = env->FindClass("[I");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_int1DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
clazz = env->FindClass("[[I");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_int2DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
//Double
clazz = env->FindClass("java/lang/Double");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_Double = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_Double_ctor = env->GetMethodID(g_cls_Double, "<init>", "(D)V");
- if (!g_mid_Double_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_Double_ctor);
clazz = env->FindClass("[D");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_double1DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
clazz = env->FindClass("[[D");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_double2DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
//Boolean
clazz = env->FindClass("java/lang/Boolean");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_Boolean = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_Boolean_ctor = env->GetMethodID(g_cls_Boolean, "<init>", "(Z)V");
- if (!g_mid_Boolean_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_Boolean_ctor);
clazz = env->FindClass("[Z");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_boolean1DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
clazz = env->FindClass("[[Z");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_boolean2DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
//String
clazz = env->FindClass("java/lang/String");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_String = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
clazz = env->FindClass("[Ljava/lang/String;");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_String1DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
clazz = env->FindClass("[[Ljava/lang/String;");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_String2DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
//LinkedList
clazz = env->FindClass("java/util/LinkedList");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_LinkedList = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_LinkedList_ctor = env->GetMethodID(g_cls_LinkedList, "<init>", "()V");
- if (!g_mid_LinkedList_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_LinkedList_ctor);
g_mid_LinkedList_add_object = env->GetMethodID(g_cls_LinkedList, "add", "(Ljava/lang/Object;)Z");
- if (!g_mid_LinkedList_add_object) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_LinkedList_add_object);
//Map
clazz = env->FindClass("java/util/Map");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_Map = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_Map_entrySet = env->GetMethodID(g_cls_Map, "entrySet", "()Ljava/util/Set;");
- if (!g_mid_Map_entrySet) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_Map_entrySet);
//MapEntry
clazz = env->FindClass("java/util/Map$Entry");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_MapEntry = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_MapEntry_getKey = env->GetMethodID(g_cls_MapEntry, "getKey", "()Ljava/lang/Object;");
- if (!g_mid_MapEntry_getKey) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_MapEntry_getKey);
g_mid_MapEntry_getValue = env->GetMethodID(g_cls_MapEntry, "getValue", "()Ljava/lang/Object;");
- if (!g_mid_MapEntry_getValue) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_MapEntry_getValue);
//Set
clazz = env->FindClass("java/util/Set");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_Set = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_Set_iterator = env->GetMethodID(g_cls_Set, "iterator", "()Ljava/util/Iterator;");
- if (!g_mid_Set_iterator) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_Set_iterator);
//Iterator
clazz = env->FindClass("java/util/Iterator");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_Iterator = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_Iterator_hasNext = env->GetMethodID(g_cls_Iterator, "hasNext", "()Z");
- if (!g_mid_Iterator_hasNext) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_Iterator_hasNext);
g_mid_Iterator_next = env->GetMethodID(g_cls_Iterator, "next", "()Ljava/lang/Object;");
- if (!g_mid_Iterator_next) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_Iterator_next);
//HashMap
clazz = env->FindClass("java/util/HashMap");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_HashMap = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_HashMap_ctor = env->GetMethodID(g_cls_HashMap, "<init>", "()V");
- if (!g_mid_HashMap_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_HashMap_ctor);
g_mid_HashMap_put = env->GetMethodID(g_cls_HashMap, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
- if (!g_mid_HashMap_put) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_HashMap_put);
//OcException
clazz = env->FindClass("org/iotivity/base/OcException");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcException = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcException_ctor = env->GetMethodID(g_cls_OcException, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");
- if (!g_mid_OcException_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcException_ctor);
g_mid_OcException_setNativeExceptionLocation = env->GetMethodID(g_cls_OcException, "setNativeExceptionLocation",
"(Ljava/lang/String;""Ljava/lang/String;""I)V");
- if (!g_mid_OcException_setNativeExceptionLocation) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcException_setNativeExceptionLocation);
//OcResource
clazz = env->FindClass("org/iotivity/base/OcResource");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcResource = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcResource_ctor = env->GetMethodID(g_cls_OcResource, "<init>", "(J)V");
- if (!g_mid_OcResource_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcResource_ctor);
//OcRepresentation
clazz = env->FindClass("org/iotivity/base/OcRepresentation");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcRepresentation = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcRepresentation_N_ctor = env->GetMethodID(g_cls_OcRepresentation, "<init>", "(J)V");
- if (!g_mid_OcRepresentation_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcRepresentation_N_ctor);
g_mid_OcRepresentation_N_ctor_bool = env->GetMethodID(g_cls_OcRepresentation, "<init>", "(JZ)V");
- if (!g_mid_OcRepresentation_N_ctor_bool) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcRepresentation_N_ctor_bool);
clazz = env->FindClass("[Lorg/iotivity/base/OcRepresentation;");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcRepresentation1DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
clazz = env->FindClass("[[Lorg/iotivity/base/OcRepresentation;");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcRepresentation2DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
//HeaderOptions
clazz = env->FindClass("org/iotivity/base/OcHeaderOption");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcHeaderOption = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcHeaderOption_ctor = env->GetMethodID(g_cls_OcHeaderOption, "<init>", "(ILjava/lang/String;)V");
- if (!g_mid_OcHeaderOption_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcHeaderOption_ctor);
g_mid_OcHeaderOption_get_id = env->GetMethodID(g_cls_OcHeaderOption, "getOptionId", "()I");
- if (!g_mid_OcHeaderOption_get_id) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcHeaderOption_get_id);
g_mid_OcHeaderOption_get_data = env->GetMethodID(g_cls_OcHeaderOption, "getOptionData", "()Ljava/lang/String;");
- if (!g_mid_OcHeaderOption_get_data) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcHeaderOption_get_data);
//OcResourceRequest
clazz = env->FindClass("org/iotivity/base/OcResourceRequest");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcResourceRequest = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcResourceRequest_N_ctor = env->GetMethodID(g_cls_OcResourceRequest, "<init>", "(J)V");
- if (!g_mid_OcResourceRequest_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcResourceRequest_N_ctor);
//OcResourceResponse
clazz = env->FindClass("org/iotivity/base/OcResourceResponse");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcResourceResponse = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcResourceResponse_N_ctor = env->GetMethodID(g_cls_OcResourceResponse, "<init>", "(J)V");
- if (!g_mid_OcResourceResponse_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcResourceResponse_N_ctor);
//OcResourceHandle
clazz = env->FindClass("org/iotivity/base/OcResourceHandle");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcResourceHandle = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcResourceHandle_N_ctor = env->GetMethodID(g_cls_OcResourceHandle, "<init>", "(J)V");
- if (!g_mid_OcResourceHandle_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcResourceHandle_N_ctor);
//OcPresenceHandle
clazz = env->FindClass("org/iotivity/base/OcPresenceHandle");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcPresenceHandle = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcPresenceHandle_N_ctor = env->GetMethodID(g_cls_OcPresenceHandle, "<init>", "(J)V");
- if (!g_mid_OcPresenceHandle_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcPresenceHandle_N_ctor);
//OcRequestHandle
clazz = env->FindClass("org/iotivity/base/OcRequestHandle");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcRequestHandle = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcRequestHandle_N_ctor = env->GetMethodID(g_cls_OcRequestHandle, "<init>", "(J)V");
- if (!g_mid_OcRequestHandle_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcRequestHandle_N_ctor);
//OcPresenceStatus
clazz = env->FindClass("org/iotivity/base/OcPresenceStatus");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcPresenceStatus = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcPresenceStatus_get = env->GetStaticMethodID(g_cls_OcPresenceStatus, "get",
"(Ljava/lang/String;)Lorg/iotivity/base/OcPresenceStatus;");
- if (!g_mid_OcPresenceStatus_get) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcPresenceStatus_get);
//ObservationInfo
clazz = env->FindClass("org/iotivity/base/ObservationInfo");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_ObservationInfo = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_ObservationInfo_N_ctor = env->GetMethodID(g_cls_ObservationInfo, "<init>", "(IB)V");
- if (!g_mid_ObservationInfo_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_ObservationInfo_N_ctor);
clazz = env->FindClass("org/iotivity/base/OcResourceIdentifier");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcResourceIdentifier = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcResourceIdentifier_N_ctor = env->GetMethodID(g_cls_OcResourceIdentifier, "<init>", "(J)V");
- if (!g_mid_OcResourceIdentifier_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcResourceIdentifier_N_ctor);
//OcSecureResource
clazz = env->FindClass("org/iotivity/base/OcSecureResource");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcSecureResource = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcSecureResource_ctor = env->GetMethodID(g_cls_OcSecureResource, "<init>", "(J)V");
- if (!g_mid_OcSecureResource_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcSecureResource_ctor);
//ProvisionResult
clazz = env->FindClass("org/iotivity/base/ProvisionResult");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcProvisionResult = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcProvisionResult_ctor = env->GetMethodID(g_cls_OcProvisionResult, "<init>", "(Ljava/lang/String;I)V");
- if (!g_mid_OcProvisionResult_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcProvisionResult_ctor);
+
+ //OcDirectPairDevice
+ clazz = env->FindClass("org/iotivity/base/OcDirectPairDevice");
+ VERIFY_VARIABLE_NULL(clazz);
+ g_cls_OcDirectPairDevice = (jclass)env->NewGlobalRef(clazz);
+ g_mid_OcDirectPairDevice_ctor = env->GetMethodID(g_cls_OcDirectPairDevice, "<init>", "(J)V");
+ VERIFY_VARIABLE_NULL(g_mid_OcDirectPairDevice_ctor);
+
+ g_mid_OcDirectPairDevice_dev_ctor = env->GetMethodID(g_cls_OcDirectPairDevice, "<init>", "(Ljava/lang/String;)V");
+ VERIFY_VARIABLE_NULL(g_mid_OcDirectPairDevice_dev_ctor);
+ env->DeleteLocalRef(clazz);
//OicSecAcl
clazz = env->FindClass("org/iotivity/base/OicSecAcl");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcOicSecAcl = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcOicSecAcl_get_subject = env->GetMethodID(g_cls_OcOicSecAcl, "getSubject", "()Ljava/lang/String;");
- if (!g_mid_OcOicSecAcl_get_subject) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_subject);
g_mid_OcOicSecAcl_get_resources_cnt = env->GetMethodID(g_cls_OcOicSecAcl, "getResourcesCount", "()I");
- if (!g_mid_OcOicSecAcl_get_resources_cnt) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_resources_cnt);
g_mid_OcOicSecAcl_get_resources = env->GetMethodID(g_cls_OcOicSecAcl, "getResources", "(I)Ljava/lang/String;");
- if (!g_mid_OcOicSecAcl_get_resources) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_resources);
g_mid_OcOicSecAcl_get_permission = env->GetMethodID(g_cls_OcOicSecAcl, "getPermission", "()I");
- if (!g_mid_OcOicSecAcl_get_permission) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_permission);
g_mid_OcOicSecAcl_get_periods_cnt = env->GetMethodID(g_cls_OcOicSecAcl, "getPeriodsCount", "()I");
- if (!g_mid_OcOicSecAcl_get_periods_cnt) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_periods_cnt);
g_mid_OcOicSecAcl_get_periods = env->GetMethodID(g_cls_OcOicSecAcl, "getPeriods", "(I)Ljava/lang/String;");
- if (!g_mid_OcOicSecAcl_get_periods) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_periods);
g_mid_OcOicSecAcl_get_recurrences = env->GetMethodID(g_cls_OcOicSecAcl, "getRecurrences", "(I)Ljava/lang/String;");
- if (!g_mid_OcOicSecAcl_get_recurrences) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_recurrences);
g_mid_OcOicSecAcl_get_rownerID = env->GetMethodID(g_cls_OcOicSecAcl, "getRownerID", "()Ljava/lang/String;");
- if (!g_mid_OcOicSecAcl_get_rownerID) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_rownerID);
+
+ //OicSecPdAcl
+ clazz = env->FindClass("org/iotivity/base/OicSecPdAcl");
+ VERIFY_VARIABLE_NULL(clazz);
+ g_cls_OcOicSecPdAcl = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_OcOicSecPdAcl_get_resources_cnt = env->GetMethodID(g_cls_OcOicSecPdAcl, "getResourcesCount", "()I");
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_resources_cnt);
+
+ g_mid_OcOicSecPdAcl_get_resources = env->GetMethodID(g_cls_OcOicSecPdAcl, "getResources", "(I)Ljava/lang/String;");
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_resources);
+
+ g_mid_OcOicSecPdAcl_get_permission = env->GetMethodID(g_cls_OcOicSecPdAcl, "getPermission", "()I");
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_permission);
+
+ g_mid_OcOicSecPdAcl_get_periods_cnt = env->GetMethodID(g_cls_OcOicSecPdAcl, "getPeriodsCount", "()I");
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_periods_cnt);
+
+ g_mid_OcOicSecPdAcl_get_periods = env->GetMethodID(g_cls_OcOicSecPdAcl, "getPeriods", "(I)Ljava/lang/String;");
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_periods);
+
+ g_mid_OcOicSecPdAcl_get_recurrences = env->GetMethodID(g_cls_OcOicSecPdAcl, "getRecurrences", "(I)Ljava/lang/String;");
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_recurrences);
return JNI_CURRENT_VERSION;
}
return;
}
+
env->DeleteGlobalRef(g_cls_Integer);
env->DeleteGlobalRef(g_cls_int1DArray);
env->DeleteGlobalRef(g_cls_int2DArray);
env->DeleteGlobalRef(g_cls_OcSecureResource);
env->DeleteGlobalRef(g_cls_OcProvisionResult);
env->DeleteGlobalRef(g_cls_OcOicSecAcl);
-}
\ No newline at end of file
+}
extern jclass g_cls_OcProvisionResult;
extern jclass g_cls_OcSecureResource;
extern jclass g_cls_OcOicSecAcl;
+extern jclass g_cls_OcOicSecPdAcl;
+extern jclass g_cls_OcDirectPairDevice;
extern jmethodID g_mid_Integer_ctor;
extern jmethodID g_mid_Double_ctor;
extern jmethodID g_mid_OcResourceIdentifier_N_ctor;
extern jmethodID g_mid_OcProvisionResult_ctor;
extern jmethodID g_mid_OcSecureResource_ctor;
+extern jmethodID g_mid_OcDirectPairDevice_ctor;
+extern jmethodID g_mid_OcDirectPairDevice_dev_ctor;
extern jmethodID g_mid_OcOicSecAcl_get_subject;
extern jmethodID g_mid_OcOicSecAcl_get_resources_cnt;
extern jmethodID g_mid_OcOicSecAcl_get_resources;
extern jmethodID g_mid_OcOicSecAcl_get_periods;
extern jmethodID g_mid_OcOicSecAcl_get_recurrences;
extern jmethodID g_mid_OcOicSecAcl_get_rownerID;
+extern jmethodID g_mid_OcOicSecPdAcl_get_resources_cnt;
+extern jmethodID g_mid_OcOicSecPdAcl_get_resources;
+extern jmethodID g_mid_OcOicSecPdAcl_get_permission;
+extern jmethodID g_mid_OcOicSecPdAcl_get_periods_cnt;
+extern jmethodID g_mid_OcOicSecPdAcl_get_periods;
+extern jmethodID g_mid_OcOicSecPdAcl_get_recurrences;
typedef void(*RemoveListenerCallback)(JNIEnv* env, jobject jListener);
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)
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
--- /dev/null
+/*
+* //******************************************************************
+* //
+* // Copyright 2016 Samsung Electronics All Rights Reserved.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+* //
+* // Licensed under the Apache License, Version 2.0 (the "License");
+* // you may not use this file except in compliance with the License.
+* // You may obtain a copy of the License at
+* //
+* // http://www.apache.org/licenses/LICENSE-2.0
+* //
+* // Unless required by applicable law or agreed to in writing, software
+* // distributed under the License is distributed on an "AS IS" BASIS,
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* // See the License for the specific language governing permissions and
+* // limitations under the License.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+*/
+#include "JniOnDPDevicesFoundListener.h"
+#include "JniOcDirectPairDevice.h"
+#include "OCApi.h"
+using namespace OC;
+
+JniOnDPDevicesFoundListener::JniOnDPDevicesFoundListener(JNIEnv *env, jobject jListener,
+ RemoveListenerCallback removeListenerCallback)
+{
+ m_jwListener = env->NewWeakGlobalRef(jListener);
+ m_removeListenerCallback = removeListenerCallback;
+}
+
+jobject JniOnDPDevicesFoundListener::convertdpDevVectorToJavaList(JNIEnv *env, PairedDevices DPdevList)
+{
+ jobject jResultList = env->NewObject(g_cls_LinkedList, g_mid_LinkedList_ctor);
+ if (!jResultList)
+ {
+ return nullptr;
+ }
+
+ for (size_t i = 0; i < DPdevList.size(); ++i)
+ {
+ JniOcDirectPairDevice *device = new JniOcDirectPairDevice(DPdevList.at(i));
+ if (!device)
+ {
+ return nullptr;
+ }
+
+ jstring jStr = env->NewStringUTF(((DPdevList.at(i))->getDeviceID()).c_str());
+ if (!jStr)
+ {
+ return nullptr;
+ }
+ jobject jresult = env->NewObject(g_cls_OcDirectPairDevice,
+ g_mid_OcDirectPairDevice_dev_ctor,jStr);
+ if (!jresult)
+ {
+ return nullptr;
+ }
+
+ SetHandle<JniOcDirectPairDevice>(env, jresult, device);
+
+ env->CallBooleanMethod(jResultList, g_mid_LinkedList_add_object, jresult);
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
+ env->DeleteLocalRef(jresult);
+ env->DeleteLocalRef(jStr);
+ }
+ return jResultList;
+}
+
+JniOnDPDevicesFoundListener::~JniOnDPDevicesFoundListener()
+{
+ LOGI("~JniOnDPDevicesFoundListener()");
+ if (m_jwListener)
+ {
+ jint ret = JNI_ERR;
+ JNIEnv *env = GetJNIEnv(ret);
+ if (nullptr == env)
+ {
+ return;
+ }
+ env->DeleteWeakGlobalRef(m_jwListener);
+ m_jwListener = nullptr;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ }
+}
+
+void JniOnDPDevicesFoundListener::directPairingDevicesCallback(PairedDevices paringDevicesList, DPFunc func)
+{
+ jint ret;
+ JNIEnv *env = GetJNIEnv(ret);
+ if (nullptr == env)
+ {
+ return;
+ }
+
+ jobject jListener = env->NewLocalRef(m_jwListener);
+ if (!jListener)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ jclass clsL = env->GetObjectClass(jListener);
+
+ if (!clsL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ jobject jpairingDevicesList = convertdpDevVectorToJavaList(env, paringDevicesList);
+ std::string calledFunc;
+ switch (func)
+ {
+ case DPFunc::FIND_DIRECT_PAIRED_DEV_LIST:
+ {
+ calledFunc = "onFindDirectPairingListener";
+ }
+ break;
+ case DPFunc::GET_PAIRED_DEV_LIST:
+ {
+ calledFunc = "onGetDirectPairedListener";
+ }
+ break;
+ default:
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ }
+ return;
+ }
+
+ jmethodID midL = env->GetMethodID(clsL, calledFunc.c_str(), "(Ljava/util/List;)V");
+
+ if (!midL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ env->CallVoidMethod(jListener, midL, jpairingDevicesList);
+ if (env->ExceptionCheck())
+ {
+ LOGE("Java exception is thrown");
+ }
+
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+}
+
+void JniOnDPDevicesFoundListener::checkExAndRemoveListener(JNIEnv* env)
+{
+ if (env->ExceptionCheck())
+ {
+ jthrowable ex = env->ExceptionOccurred();
+ env->ExceptionClear();
+ m_removeListenerCallback(env, m_jwListener);
+ env->Throw((jthrowable)ex);
+ }
+ else
+ {
+ m_removeListenerCallback(env, m_jwListener);
+ }
+}
--- /dev/null
+/*
+* //******************************************************************
+* //
+* // 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
{
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
-
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnDeleteListener::onDeleteCallback(const HeaderOptions& headerOptions, const int eCode)
{
- jint envRet;
+ jint envRet = JNI_ERR;
JNIEnv *env = GetJNIEnv(envRet);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jclass clsL = env->GetObjectClass(jListener);
if (!clsL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!ex)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onDeleteFailed", "(Ljava/lang/Throwable;)V");
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, ex);
if (!jHeaderOptionList)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, jHeaderOptionList);
}
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnDeleteListener::checkExAndRemoveListener(JNIEnv* env)
{
m_ownerResource->removeOnDeleteListener(env, m_jwListener);
}
-}
\ No newline at end of file
+}
LOGI("~JniOnDeviceInfoListener");
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnDeviceInfoListener::foundDeviceCallback(const OC::OCRepresentation& ocRepresentation)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
LOGI("Java onDeviceInfoListener object is already destroyed, quiting");
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onDeviceFound", "(Lorg/iotivity/base/OcRepresentation;)V");
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
checkExAndRemoveListener(env);
}
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnDeviceInfoListener::checkExAndRemoveListener(JNIEnv* env)
{
m_removeListenerCallback(env, m_jwListener);
}
-}
\ No newline at end of file
+}
--- /dev/null
+/*
+* //******************************************************************
+* //
+* // Copyright 2016 Samsung Electronics All Rights Reserved.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+* //
+* // Licensed under the Apache License, Version 2.0 (the "License");
+* // you may not use this file except in compliance with the License.
+* // You may obtain a copy of the License at
+* //
+* // http://www.apache.org/licenses/LICENSE-2.0
+* //
+* // Unless required by applicable law or agreed to in writing, software
+* // distributed under the License is distributed on an "AS IS" BASIS,
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* // See the License for the specific language governing permissions and
+* // limitations under the License.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+*/
+#include "JniOnDirectPairingListener.h"
+#include "JniOcDirectPairDevice.h"
+#include "OCDirectPairing.h"
+#include "OCApi.h"
+using namespace OC;
+
+JniOnDirectPairingListener::JniOnDirectPairingListener(JNIEnv *env, jobject jListener,
+ RemoveListenerCallback removeListenerCallback)
+{
+ m_jwListener = env->NewWeakGlobalRef(jListener);
+ m_removeListenerCallback = removeListenerCallback;
+}
+
+
+JniOnDirectPairingListener::~JniOnDirectPairingListener()
+{
+ LOGI("~JniOnDirectPairingListener()");
+ if (m_jwListener)
+ {
+ jint ret = JNI_ERR;
+ JNIEnv *env = GetJNIEnv(ret);
+ if (nullptr == env)
+ {
+ return;
+ }
+ env->DeleteWeakGlobalRef(m_jwListener);
+ m_jwListener = nullptr;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ }
+}
+
+void JniOnDirectPairingListener::doDirectPairingCB(std::shared_ptr<OC::OCDirectPairing> dpDev,
+ OCStackResult result)
+{
+ jint ret = JNI_ERR;
+ JNIEnv *env = GetJNIEnv(ret);
+ if (nullptr == env)
+ {
+ return;
+ }
+
+ jobject jListener = env->NewLocalRef(m_jwListener);
+ if (!jListener)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ jclass clsL = env->GetObjectClass(jListener);
+ if (!clsL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ JniOcDirectPairDevice *device = new JniOcDirectPairDevice(dpDev);
+ if (!device)
+ {
+ return;
+ }
+
+ jstring jStr = env->NewStringUTF((dpDev->getDeviceID()).c_str());
+ if (!jStr)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ jobject jresult = env->NewObject(g_cls_OcDirectPairDevice, g_mid_OcDirectPairDevice_ctor);
+ if (!jresult)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ SetHandle<JniOcDirectPairDevice>(env, jresult, device);
+
+ jint jres = static_cast<jint>(result);
+
+ jmethodID midL = env->GetMethodID(clsL, "onDirectPairingListener", "(Ljava/lang/String;I)V");
+
+ if (!midL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ env->CallVoidMethod(jListener, midL, jStr, jres);
+ if (env->ExceptionCheck())
+ {
+ LOGE("Java exception is thrown");
+ }
+
+ checkExAndRemoveListener(env);
+
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+}
+
+void JniOnDirectPairingListener::checkExAndRemoveListener(JNIEnv* env)
+{
+ if (env->ExceptionCheck())
+ {
+ jthrowable ex = env->ExceptionOccurred();
+ env->ExceptionClear();
+ m_removeListenerCallback(env, m_jwListener);
+ env->Throw((jthrowable)ex);
+ }
+ else
+ {
+ m_removeListenerCallback(env, m_jwListener);
+ }
+}
--- /dev/null
+/*
+* //******************************************************************
+* //
+* // 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
LOGD("~JniOnGetListener");
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
const OCRepresentation& ocRepresentation, const int eCode)
{
- jint envRet;
+ jint envRet = JNI_ERR;
JNIEnv *env = GetJNIEnv(envRet);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jclass clsL = env->GetObjectClass(jListener);
if (!clsL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!ex)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onGetFailed", "(Ljava/lang/Throwable;)V");
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, ex);
if (!jHeaderOptionList)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, jHeaderOptionList, jRepresentation);
}
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnGetListener::checkExAndRemoveListener(JNIEnv* env)
{
m_ownerResource->removeOnGetListener(env, m_jwListener);
}
-}
\ No newline at end of file
+}
{
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,
const OCRepresentation& ocRepresentation, const int& eCode, const int& sequenceNumber)
{
- jint envRet;
+ jint envRet = JNI_ERR;
JNIEnv *env = GetJNIEnv(envRet);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jclass clsL = env->GetObjectClass(jListener);
if (!clsL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!ex)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onObserveFailed", "(Ljava/lang/Throwable;)V");
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, ex);
if (!jHeaderOptionList)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
}
}
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnObserveListener::checkExAndRemoveListener(JNIEnv* env)
{
m_ownerResource->removeOnObserveListener(env, m_jwListener);
}
-}
\ No newline at end of file
+}
LOGI("~JniOnPlatformInfoListener");
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnPlatformInfoListener::foundPlatformCallback(const OC::OCRepresentation& ocRepresentation)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
LOGI("Java onPlatformInfoListener object is already destroyed, quiting");
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onPlatformFound", "(Lorg/iotivity/base/OcRepresentation;)V");
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
checkExAndRemoveListener(env);
}
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnPlatformInfoListener::checkExAndRemoveListener(JNIEnv* env)
{
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnPostListener::onPostCallback(const HeaderOptions& headerOptions,
const OCRepresentation& ocRepresentation, const int eCode)
{
- jint envRet;
+ jint envRet = JNI_ERR;
JNIEnv *env = GetJNIEnv(envRet);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jclass clsL = env->GetObjectClass(jListener);
if (!clsL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!ex)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onPostFailed", "(Ljava/lang/Throwable;)V");
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, ex);
if (!jHeaderOptionList)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
}
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnPostListener::checkExAndRemoveListener(JNIEnv* env)
{
m_ownerResource->removeOnPostListener(env, m_jwListener);
}
-}
\ No newline at end of file
+}
LOGD("~JniOnPresenceListener");
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
const std::string& hostAddress)
{
LOGI("JniOnPresenceListener::onPresenceCallback");
- if (!m_jwListener) return;
+ if (!m_jwListener)
+ {
+ return;
+ }
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
if (OC_STACK_OK != result && OC_STACK_PRESENCE_STOPPED != result &&
OC_STACK_PRESENCE_TIMEOUT != result && OC_STACK_PRESENCE_DO_NOT_HANDLE != result)
{
ThrowOcException(result, "onPresenceCallback: stack failure");
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (enumField.empty())
{
ThrowOcException(JNI_INVALID_VALUE, "Unexpected OCStackResult value");
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!jPresenceStatus)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!clsL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onPresence",
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
LOGE("Java exception is thrown");
checkExAndRemoveListener(env);
}
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnPresenceListener::checkExAndRemoveListener(JNIEnv* env)
jweak JniOnPresenceListener::getJWListener()
{
return this->m_jwListener;
-}
\ No newline at end of file
+}
{
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnPutListener::onPutCallback(const HeaderOptions& headerOptions,
const OCRepresentation& ocRepresentation, const int eCode)
{
- jint envRet;
+ jint envRet = JNI_ERR;
JNIEnv *env = GetJNIEnv(envRet);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jclass clsL = env->GetObjectClass(jListener);
if (!clsL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!ex)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onPutFailed", "(Ljava/lang/Throwable;)V");
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, ex);
if (!jHeaderOptionList)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
}
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnPutListener::checkExAndRemoveListener(JNIEnv* env)
{
m_ownerResource->removeOnPutListener(env, m_jwListener);
}
-}
\ No newline at end of file
+}
LOGI("~JniOnResourceFoundListener()");
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnResourceFoundListener::foundResourceCallback(std::shared_ptr<OC::OCResource> resource)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
jobject jResource = env->NewObject(g_cls_OcResource, g_mid_OcResource_ctor);
if (!jResource)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
JniOcResource *jniOcResource = new JniOcResource(resource);
{
delete jniOcResource;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
jclass clsL = env->GetObjectClass(jListener);
if (!clsL)
{
delete jniOcResource;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
jmethodID midL = env->GetMethodID(clsL, "onResourceFound", "(Lorg/iotivity/base/OcResource;)V");
if (!midL)
{
delete jniOcResource;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
env->CallVoidMethod(jListener, midL, jResource);
if (env->ExceptionCheck())
LOGE("Java exception is thrown");
delete jniOcResource;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnResourceFoundListener::checkExAndRemoveListener(JNIEnv* env)
{
m_removeListenerCallback(env, m_jwListener);
}
-}
\ No newline at end of file
+}
LOGI("~JniPinCheckListener()");
if (m_jListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (NULL == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteGlobalRef(m_jListener);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniPinCheckListener::PinCallback(char *pinBuf, size_t bufSize)
{
- jint ret;
-
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (NULL == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jclass clsL = env->GetObjectClass(m_jListener);
if (!clsL)
{
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "pinCallbackListener", "()Ljava/lang/String;");
if (!midL)
{
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jstring jpin = (jstring)env->CallObjectMethod(m_jListener, midL);
if (env->ExceptionCheck())
{
LOGE("Java exception is thrown");
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
OICStrcpy(pinBuf, bufSize, str);
env->ReleaseStringUTFChars(jpin, str);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
LOGI("~JniProvisionResultListner()");
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (NULL == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result, int hasError,
ListenerFunc func)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (NULL == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!clsL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!jResultList)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
calledFunc = "provisionPairwiseDevicesListener";
}
break;
+ case ListenerFunc::PROVISIONDIRECTPAIRING:
+ {
+ calledFunc = "provisionDirectPairingListener";
+ }
+ break;
default:
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
}
return;
}
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, jResultList, (jint)hasError);
}
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniProvisionResultListner::checkExAndRemoveListener(JNIEnv* env)
PROVISIONCREDENTIALS,
UNLINKDEVICES,
REMOVEDEVICE,
- PROVISIONPAIRWISEDEVICES
+ PROVISIONPAIRWISEDEVICES,
+ PROVISIONDIRECTPAIRING
};
class JniProvisionResultListner
return OC_STACK_OK;
}
+
+OCStackResult JniSecureUtils::convertJavaPdACLToOCAcl(JNIEnv *env, jobject in, OicSecPdAcl_t *pdacl)
+{
+ jstring jData;
+ jvalue args[1];
+
+ jint jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecPdAcl_get_resources_cnt);
+ if (!jCount || env->ExceptionCheck())
+ {
+ return OC_STACK_ERROR;
+ }
+
+ pdacl->resourcesLen = jCount;
+ pdacl->resources = new char*[jCount];
+
+ if (!pdacl->resources)
+ {
+ return OC_STACK_ERROR;
+ }
+ for (jint i = 0; i < jCount; ++i)
+ {
+ args[0].i = i;
+ jData = (jstring) env->CallObjectMethodA(in, g_mid_OcOicSecPdAcl_get_resources, args);
+ if (!jData || env->ExceptionCheck())
+ {
+ return OC_STACK_ERROR;
+ }
+
+ pdacl->resources[i] = (char*) env->GetStringUTFChars(jData, 0);
+ }
+
+ jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecPdAcl_get_permission);
+ if (env->ExceptionCheck())
+ {
+ return OC_STACK_ERROR;
+ }
+
+ pdacl->permission = jCount;
+ jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecPdAcl_get_periods_cnt);
+ if (env->ExceptionCheck())
+ {
+ return OC_STACK_ERROR;
+ }
+
+ pdacl->prdRecrLen = jCount;
+ if (jCount)
+ {
+ pdacl->periods = new char*[jCount];
+ if (!pdacl->periods)
+ {
+ return OC_STACK_ERROR;
+ }
+ }
+ for (jint i = 0; i < jCount; ++i)
+ {
+ args[0].i = i;
+ jData = (jstring) env->CallObjectMethodA(in, g_mid_OcOicSecPdAcl_get_periods, args);
+ if (!jData || env->ExceptionCheck())
+ {
+ return OC_STACK_ERROR;
+ }
+
+ pdacl->periods[i] = (char*) env->GetStringUTFChars(jData, 0);
+ }
+
+ if (jCount)
+ {
+ pdacl->recurrences = new char*[jCount];
+ if (!pdacl->recurrences)
+ {
+ return OC_STACK_ERROR;
+ }
+ }
+ for (jint i = 0; i < jCount; ++i)
+ {
+ args[0].i = i;
+ jData = (jstring) env->CallObjectMethodA(in, g_mid_OcOicSecPdAcl_get_recurrences, args);
+ if (!jData || env->ExceptionCheck())
+ {
+ return OC_STACK_ERROR;
+ }
+
+ pdacl->recurrences[i] = (char*) env->GetStringUTFChars(jData, 0);
+ }
+ return OC_STACK_OK;
+}
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);
};
jobject JniUtils::convertStrVectorToJavaStrList(JNIEnv *env, std::vector<std::string> &vector)
{
jobject jList = env->NewObject(g_cls_LinkedList, g_mid_LinkedList_ctor);
- if (!jList) return nullptr;
+ if (!jList)
+ {
+ return nullptr;
+ }
for (size_t i = 0; i < vector.size(); ++i)
{
jstring jStr = env->NewStringUTF(vector[i].c_str());
- if (!jStr) return nullptr;
+ if (!jStr)
+ {
+ return nullptr;
+ }
env->CallBooleanMethod(jList, g_mid_LinkedList_add_object, jStr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jStr);
}
return jList;
void JniUtils::convertJavaStrArrToStrVector(JNIEnv *env, jobjectArray jStrArr, std::vector<std::string> &vector)
{
- if (!jStrArr) return;
+ if (!jStrArr)
+ {
+ return;
+ }
jsize len = env->GetArrayLength(jStrArr);
for (jsize i = 0; i < len; ++i)
{
jstring jStr = (jstring)env->GetObjectArrayElement(jStrArr, i);
- if (!jStr) return;
+ if (!jStr)
+ {
+ return;
+ }
vector.push_back(env->GetStringUTFChars(jStr, nullptr));
- if (env->ExceptionCheck()) return;
+ if (env->ExceptionCheck())
+ {
+ return;
+ }
env->DeleteLocalRef(jStr);
}
}
void JniUtils::convertJavaHeaderOptionsArrToVector(JNIEnv *env, jobjectArray jHeaderOptions,
OC::HeaderOptions &headerOptions)
{
- if (!jHeaderOptions) return;
+ if (!jHeaderOptions)
+ {
+ return;
+ }
+
jsize len = env->GetArrayLength(jHeaderOptions);
for (jsize i = 0; i < len; ++i)
{
jobject header = env->GetObjectArrayElement(jHeaderOptions, i);
- if (!header) return;
+ if (!header)
+ {
+ return;
+ }
jint jId = env->CallIntMethod(header, g_mid_OcHeaderOption_get_id);
jstring jData = (jstring)env->CallObjectMethod(header, g_mid_OcHeaderOption_get_data);
OC::HeaderOption::OCHeaderOption hopt(
headerOptions.push_back(hopt);
- if (env->ExceptionCheck()) return;
+ if (env->ExceptionCheck())
+ {
+ return;
+ }
env->DeleteLocalRef(header);
env->DeleteLocalRef(jData);
}
jobject JniUtils::convertHeaderOptionsVectorToJavaList(JNIEnv *env, const OC::HeaderOptions& headerOptions)
{
jobject jHeaderOptionList = env->NewObject(g_cls_LinkedList, g_mid_LinkedList_ctor);
- if (!jHeaderOptionList) return nullptr;
+ if (!jHeaderOptionList)
+ {
+ return nullptr;
+ }
for (size_t i = 0; i < headerOptions.size(); ++i)
{
static_cast<jint>(headerOptions[i].getOptionID()),
env->NewStringUTF(headerOptions[i].getOptionData().c_str())
);
- if (!jHeaderOption) return nullptr;
+ if (!jHeaderOption)
+ {
+ return nullptr;
+ }
env->CallBooleanMethod(jHeaderOptionList, g_mid_LinkedList_add_object, jHeaderOption);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jHeaderOption);
}
void JniUtils::convertJavaMapToQueryParamsMap(JNIEnv *env, jobject hashMap, OC::QueryParamsMap &map)
{
- if (!hashMap) return;
+ if (!hashMap)
+ {
+ return;
+ }
jobject jEntrySet = env->CallObjectMethod(hashMap, g_mid_Map_entrySet);
jobject jIterator = env->CallObjectMethod(jEntrySet, g_mid_Set_iterator);
- if (!jEntrySet || !jIterator || env->ExceptionCheck()) return;
+ if (!jEntrySet || !jIterator || env->ExceptionCheck())
+ {
+ return;
+ }
while (env->CallBooleanMethod(jIterator, g_mid_Iterator_hasNext))
{
jobject jEntry = env->CallObjectMethod(jIterator, g_mid_Iterator_next);
- if (!jEntry) return;
+ if (!jEntry)
+ {
+ return;
+ }
jstring jKey = (jstring)env->CallObjectMethod(jEntry, g_mid_MapEntry_getKey);
- if (!jKey) return;
+ if (!jKey)
+ {
+ return;
+ }
jstring jValue = (jstring)env->CallObjectMethod(jEntry, g_mid_MapEntry_getValue);
- if (!jValue) return;
+ if (!jValue)
+ {
+ return;
+ }
map.insert(std::make_pair(env->GetStringUTFChars(jKey, nullptr),
env->GetStringUTFChars(jValue, nullptr)));
- if (env->ExceptionCheck()) return;
+ if (env->ExceptionCheck())
+ {
+ return;
+ }
env->DeleteLocalRef(jEntry);
env->DeleteLocalRef(jKey);
env->DeleteLocalRef(jValue);
jobject JniUtils::convertQueryParamsMapToJavaMap(JNIEnv *env, const OC::QueryParamsMap &map)
{
jobject hashMap = env->NewObject(g_cls_HashMap, g_mid_HashMap_ctor);
- if (!hashMap) return nullptr;
+ if (!hashMap)
+ {
+ return nullptr;
+ }
for (auto it = map.begin(); it != map.end(); ++it)
{
g_mid_HashMap_put,
env->NewStringUTF(key.c_str()),
env->NewStringUTF(value.c_str()));
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
}
return hashMap;
jobjectArray jRepresentationArray,
std::vector<OC::OCRepresentation>& representationVector)
{
- if (!jRepresentationArray) return;
+ if (!jRepresentationArray)
+ {
+ return;
+ }
jsize len = env->GetArrayLength(jRepresentationArray);
for (jsize i = 0; i < len; ++i)
{
jobject jRep = env->GetObjectArrayElement(jRepresentationArray, i);
- if (!jRep) return;
+ if (!jRep)
+ {
+ return;
+ }
OC::OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, jRep);
representationVector.push_back(*rep);
- if (env->ExceptionCheck()) return;
+ if (env->ExceptionCheck())
+ {
+ return;
+ }
env->DeleteLocalRef(jRep);
}
}
{
jsize len = static_cast<jsize>(representationVector.size());
jobjectArray repArr = env->NewObjectArray(len, g_cls_OcRepresentation, nullptr);
- if (!repArr) return nullptr;
+ if (!repArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < len; ++i)
{
OCRepresentation* rep = new OCRepresentation(representationVector[i]);
return nullptr;
}
env->SetObjectArrayElement(repArr, i, jRepresentation);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jRepresentation);
}
return repArr;
-}
\ No newline at end of file
+}
static OC::ServiceType getServiceType(JNIEnv *env, int type)
{
- switch (type) {
- case 0:
- return OC::ServiceType::InProc;
- case 1:
- return OC::ServiceType::OutOfProc;
- default:
- ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected service type");
- return OC::ServiceType::OutOfProc;
+ switch (type)
+ {
+ case 0:
+ return OC::ServiceType::InProc;
+ case 1:
+ return OC::ServiceType::OutOfProc;
+ default:
+ ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected service type");
+ return OC::ServiceType::OutOfProc;
};
}
static OC::ModeType getModeType(JNIEnv *env, int type)
{
- switch (type) {
- case 0:
- return OC::ModeType::Server;
- case 1:
- return OC::ModeType::Client;
- case 2:
- return OC::ModeType::Both;
- case 3:
- return OC::ModeType::Gateway;
- default:
- ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected mode type");
- return OC::ModeType::Both;
+ switch (type)
+ {
+ case 0:
+ return OC::ModeType::Server;
+ case 1:
+ return OC::ModeType::Client;
+ case 2:
+ return OC::ModeType::Both;
+ case 3:
+ return OC::ModeType::Gateway;
+ default:
+ ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected mode type");
+ return OC::ModeType::Both;
};
}
static OC::QualityOfService getQOS(JNIEnv *env, int type)
{
- switch (type) {
- case 0:
- return OC::QualityOfService::LowQos;
- case 1:
- return OC::QualityOfService::MidQos;
- case 2:
- return OC::QualityOfService::HighQos;
- case 3:
- return OC::QualityOfService::NaQos;
- default:
- ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected quality of service");
- return OC::QualityOfService::NaQos;
+ switch (type)
+ {
+ case 0:
+ return OC::QualityOfService::LowQos;
+ case 1:
+ return OC::QualityOfService::MidQos;
+ case 2:
+ return OC::QualityOfService::HighQos;
+ case 3:
+ return OC::QualityOfService::NaQos;
+ default:
+ ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected quality of service");
+ return OC::QualityOfService::NaQos;
};
}
static OC::ObserveType getObserveType(JNIEnv *env, int type)
{
- switch (type) {
- case 0:
- return OC::ObserveType::Observe;
- case 1:
- return OC::ObserveType::ObserveAll;
- default:
- ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected observe type");
- return OC::ObserveType::ObserveAll;
+ switch (type)
+ {
+ case 0:
+ return OC::ObserveType::Observe;
+ case 1:
+ return OC::ObserveType::ObserveAll;
+ default:
+ ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected observe type");
+ return OC::ObserveType::ObserveAll;
};
}
static OCEntityHandlerResult getOCEntityHandlerResult(JNIEnv *env, int type)
{
- switch (type) {
- case 0:
- return OCEntityHandlerResult::OC_EH_OK;
- case 1:
- return OCEntityHandlerResult::OC_EH_ERROR;
- case 2:
- return OCEntityHandlerResult::OC_EH_RESOURCE_CREATED;
- case 3:
- return OCEntityHandlerResult::OC_EH_RESOURCE_DELETED;
- case 4:
- return OCEntityHandlerResult::OC_EH_SLOW;
- case 5:
- return OCEntityHandlerResult::OC_EH_FORBIDDEN;
- case 6:
- return OCEntityHandlerResult::OC_EH_RESOURCE_NOT_FOUND;
- default:
- ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected OCEntityHandlerResult");
- return OCEntityHandlerResult::OC_EH_ERROR;
+ switch (type)
+ {
+ case 0:
+ return OCEntityHandlerResult::OC_EH_OK;
+ case 1:
+ return OCEntityHandlerResult::OC_EH_ERROR;
+ case 2:
+ return OCEntityHandlerResult::OC_EH_RESOURCE_CREATED;
+ case 3:
+ return OCEntityHandlerResult::OC_EH_RESOURCE_DELETED;
+ case 4:
+ return OCEntityHandlerResult::OC_EH_SLOW;
+ case 5:
+ return OCEntityHandlerResult::OC_EH_FORBIDDEN;
+ case 6:
+ return OCEntityHandlerResult::OC_EH_RESOURCE_NOT_FOUND;
+ default:
+ ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected OCEntityHandlerResult");
+ return OCEntityHandlerResult::OC_EH_ERROR;
};
}
{
switch (result)
{
- /** Success status code - START HERE.*/
- case OC_STACK_OK:
- return "OK";
- case OC_STACK_RESOURCE_CREATED:
- return "RESOURCE_CREATED";
- case OC_STACK_RESOURCE_DELETED:
- return "RESOURCE_DELETED";
- case OC_STACK_CONTINUE:
- return "CONTINUE";
- /* Error status code - START HERE */
- case OC_STACK_INVALID_URI:
- return "INVALID_URI";
- case OC_STACK_INVALID_QUERY:
- return "INVALID_QUERY";
- case OC_STACK_INVALID_IP:
- return "INVALID_IP";
- case OC_STACK_INVALID_PORT:
- return "INVALID_PORT";
- case OC_STACK_INVALID_CALLBACK:
- return "INVALID_CALLBACK";
- case OC_STACK_INVALID_METHOD:
- return "INVALID_METHOD";
- /** Invalid parameter.*/
- case OC_STACK_INVALID_PARAM:
- return "INVALID_PARAM";
- case OC_STACK_INVALID_OBSERVE_PARAM:
- return "INVALID_OBSERVE_PARAM";
- case OC_STACK_NO_MEMORY:
- return "NO_MEMORY";
- case OC_STACK_COMM_ERROR:
- return "COMM_ERROR";
- case OC_STACK_TIMEOUT:
- return "TIMEOUT";
- case OC_STACK_ADAPTER_NOT_ENABLED:
- return "ADAPTER_NOT_ENABLED";
- case OC_STACK_NOTIMPL:
- return "NOTIMPL";
- /** Resource not found.*/
- case OC_STACK_NO_RESOURCE:
- return "NO_RESOURCE";
- /** e.g: not supported method or interface.*/
- case OC_STACK_RESOURCE_ERROR:
- return "RESOURCE_ERROR";
- case OC_STACK_SLOW_RESOURCE:
- return "SLOW_RESOURCE";
- case OC_STACK_DUPLICATE_REQUEST:
- return "DUPLICATE_REQUEST";
- /** Resource has no registered observers.*/
- case OC_STACK_NO_OBSERVERS:
- return "NO_OBSERVERS";
- case OC_STACK_OBSERVER_NOT_FOUND:
- return "OBSERVER_NOT_FOUND";
- case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
- return "VIRTUAL_DO_NOT_HANDLE";
- case OC_STACK_INVALID_OPTION:
- return "INVALID_OPTION";
- /** The remote reply contained malformed data.*/
- case OC_STACK_MALFORMED_RESPONSE:
- return "MALFORMED_RESPONSE";
- case OC_STACK_PERSISTENT_BUFFER_REQUIRED:
- return "PERSISTENT_BUFFER_REQUIRED";
- case OC_STACK_INVALID_REQUEST_HANDLE:
- return "INVALID_REQUEST_HANDLE";
- case OC_STACK_INVALID_DEVICE_INFO:
- return "INVALID_DEVICE_INFO";
- case OC_STACK_INVALID_JSON:
- return "INVALID_JSON";
- /** Request is not authorized by Resource Server. */
- case OC_STACK_UNAUTHORIZED_REQ:
- return "UNAUTHORIZED_REQ";
- /** Error code from PDM */
- case OC_STACK_PDM_IS_NOT_INITIALIZED:
- return "PDM_IS_NOT_INITIALIZED";
- case OC_STACK_DUPLICATE_UUID:
- return "DUPLICATE_UUID";
- case OC_STACK_INCONSISTENT_DB:
- return "INCONSISTENT_DB";
- /** Error code from OTM */
- case OC_STACK_AUTHENTICATION_FAILURE:
- return "AUTHENTICATION_FAILURE";
- /** Insert all new error codes here!.*/
+ /** Success status code - START HERE.*/
+ case OC_STACK_OK:
+ return "OK";
+ case OC_STACK_RESOURCE_CREATED:
+ return "RESOURCE_CREATED";
+ case OC_STACK_RESOURCE_DELETED:
+ return "RESOURCE_DELETED";
+ case OC_STACK_CONTINUE:
+ return "CONTINUE";
+ /* Error status code - START HERE */
+ case OC_STACK_INVALID_URI:
+ return "INVALID_URI";
+ case OC_STACK_INVALID_QUERY:
+ return "INVALID_QUERY";
+ case OC_STACK_INVALID_IP:
+ return "INVALID_IP";
+ case OC_STACK_INVALID_PORT:
+ return "INVALID_PORT";
+ case OC_STACK_INVALID_CALLBACK:
+ return "INVALID_CALLBACK";
+ case OC_STACK_INVALID_METHOD:
+ return "INVALID_METHOD";
+ /** Invalid parameter.*/
+ case OC_STACK_INVALID_PARAM:
+ return "INVALID_PARAM";
+ case OC_STACK_INVALID_OBSERVE_PARAM:
+ return "INVALID_OBSERVE_PARAM";
+ case OC_STACK_NO_MEMORY:
+ return "NO_MEMORY";
+ case OC_STACK_COMM_ERROR:
+ return "COMM_ERROR";
+ case OC_STACK_TIMEOUT:
+ return "TIMEOUT";
+ case OC_STACK_ADAPTER_NOT_ENABLED:
+ return "ADAPTER_NOT_ENABLED";
+ case OC_STACK_NOTIMPL:
+ return "NOTIMPL";
+ /** Resource not found.*/
+ case OC_STACK_NO_RESOURCE:
+ return "NO_RESOURCE";
+ /** e.g: not supported method or interface.*/
+ case OC_STACK_RESOURCE_ERROR:
+ return "RESOURCE_ERROR";
+ case OC_STACK_SLOW_RESOURCE:
+ return "SLOW_RESOURCE";
+ case OC_STACK_DUPLICATE_REQUEST:
+ return "DUPLICATE_REQUEST";
+ /** Resource has no registered observers.*/
+ case OC_STACK_NO_OBSERVERS:
+ return "NO_OBSERVERS";
+ case OC_STACK_OBSERVER_NOT_FOUND:
+ return "OBSERVER_NOT_FOUND";
+ case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
+ return "VIRTUAL_DO_NOT_HANDLE";
+ case OC_STACK_INVALID_OPTION:
+ return "INVALID_OPTION";
+ /** The remote reply contained malformed data.*/
+ case OC_STACK_MALFORMED_RESPONSE:
+ return "MALFORMED_RESPONSE";
+ case OC_STACK_PERSISTENT_BUFFER_REQUIRED:
+ return "PERSISTENT_BUFFER_REQUIRED";
+ case OC_STACK_INVALID_REQUEST_HANDLE:
+ return "INVALID_REQUEST_HANDLE";
+ case OC_STACK_INVALID_DEVICE_INFO:
+ return "INVALID_DEVICE_INFO";
+ case OC_STACK_INVALID_JSON:
+ return "INVALID_JSON";
+ /** Request is not authorized by Resource Server. */
+ case OC_STACK_UNAUTHORIZED_REQ:
+ return "UNAUTHORIZED_REQ";
+ /** Error code from PDM */
+ case OC_STACK_PDM_IS_NOT_INITIALIZED:
+ return "PDM_IS_NOT_INITIALIZED";
+ case OC_STACK_DUPLICATE_UUID:
+ return "DUPLICATE_UUID";
+ case OC_STACK_INCONSISTENT_DB:
+ return "INCONSISTENT_DB";
+ /** Error code from OTM */
+ case OC_STACK_AUTHENTICATION_FAILURE:
+ return "AUTHENTICATION_FAILURE";
+ /** Insert all new error codes here!.*/
#ifdef WITH_PRESENCE
- case OC_STACK_PRESENCE_STOPPED:
- return "PRESENCE_STOPPED";
- case OC_STACK_PRESENCE_TIMEOUT:
- return "PRESENCE_TIMEOUT";
- case OC_STACK_PRESENCE_DO_NOT_HANDLE:
- return "PRESENCE_DO_NOT_HANDLE";
+ case OC_STACK_PRESENCE_STOPPED:
+ return "PRESENCE_STOPPED";
+ case OC_STACK_PRESENCE_TIMEOUT:
+ return "PRESENCE_TIMEOUT";
+ case OC_STACK_PRESENCE_DO_NOT_HANDLE:
+ return "PRESENCE_DO_NOT_HANDLE";
#endif
- case OC_STACK_ERROR:
- return "ERROR";
+ case OC_STACK_ERROR:
+ return "ERROR";
- case JNI_EXCEPTION:
- return "JNI_EXCEPTION";
- case JNI_NO_NATIVE_POINTER:
- return "JNI_NO_NATIVE_POINTER";
- case JNI_INVALID_VALUE:
- return "JNI_INVALID_VALUE";
- default:
- return "";
+ case JNI_EXCEPTION:
+ return "JNI_EXCEPTION";
+ case JNI_NO_NATIVE_POINTER:
+ return "JNI_NO_NATIVE_POINTER";
+ case JNI_INVALID_VALUE:
+ return "JNI_INVALID_VALUE";
+ default:
+ return "";
}
}
};
import android.test.InstrumentationTestCase;
import android.util.Log;
+import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
}
};
- OcDeviceInfo devInfo = new OcDeviceInfo("myDeviceName");
+ OcDeviceInfo devInfo = new OcDeviceInfo(
+ "myDeviceName",
+ Arrays.asList(new String[]{"oic.d.test"})
+ );
try {
//server
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;
+ }
}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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;
+ }
+}
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;
/**
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
*/
--- /dev/null
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * // http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+/**\r
+ * @brief direct pairing Method Type.\r
+ * 0: not allowed\r
+ * 1: pre-configured pin\r
+ * 2: random pin\r
+ */\r
+package org.iotivity.base;\r
+\r
+public enum OcPrmType {\r
+ DP_INVALID (-1),\r
+ DP_NOT_ALLOWED (0),\r
+ DP_PRE_CONFIGURED (1 << 0),\r
+ DP_RANDOM_PIN (1 << 1);\r
+\r
+ private int value;\r
+\r
+ private OcPrmType(int value) {\r
+ this.value = value;\r
+ }\r
+\r
+ public int getValue() {\r
+ return this.value;\r
+ }\r
+\r
+ public static OcPrmType convertOcPrmType(int value) {\r
+ switch (value)\r
+ {\r
+ case 0:\r
+ return OcPrmType.DP_NOT_ALLOWED;\r
+ case 1:\r
+ return OcPrmType.DP_PRE_CONFIGURED;\r
+ case 2:\r
+ return OcPrmType.DP_RANDOM_PIN;\r
+ }\r
+ return OcPrmType.DP_INVALID;\r
+ }\r
+}\r
import java.security.InvalidParameterException;
import java.util.Arrays;
import java.util.List;
+import java.util.Map;
/**
*
this.mNativeNeedsDelete = nativeNeedsDelete;
}
+ public native Map<String, Object> getValues();
+
public <T> T getValue(String key) throws OcException {
Object obj = this.getValueN(key);
@SuppressWarnings("unchecked")
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.
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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);
+ }
+}
private static Context mContext;
private CaBtPairingInterface(Context context) {
- mContext = context;
+ synchronized(CaBtPairingInterface.class) {
+ mContext = context;
+ }
registerIntentFilter();
}
private static Context mContext;
private CaEdrInterface(Context context) {
- mContext = context;
+ synchronized(CaEdrInterface.class) {
+ mContext = context;
+ }
registerIntentFilter();
}
private static native void caBtPairingStartScan();
private static native void caBtPairingStopScan();
private static native void caBtPairingCreateBond(BluetoothDevice device);
+
+ /**
+ * set BLE scan interval time and working count.
+ * scanning logic (start scan -> stop scan) will be worked repeatly for workingCount.
+ * and if you choose '0' value for workingCount parameter,
+ * scanning will be worked continually as interval time.
+ * @param intervalTime interval time(Seconds).
+ * @param workingCount working count with interval time.
+ */
+
+ public synchronized static void setLeScanIntervalTime(int intervalTime, int workingCount){
+ CaInterface.setLeScanIntervalTimeImpl(intervalTime, workingCount);
+ }
+
+ private static native void setLeScanIntervalTimeImpl(int intervalTime, int workingCount);
}
}\r
\r
private CaIpInterface(Context context) {\r
- mContext = context;\r
+ synchronized(CaIpInterface.class) {\r
+ mContext = context;\r
+ }\r
registerIpStateReceiver();\r
}\r
\r
private CaLeClientInterface(Context context) {
caLeRegisterLeScanCallback(mLeScanCallback);
caLeRegisterGattCallback(mGattCallback);
- mContext = context;
+ synchronized(CaLeClientInterface.class) {
+ mContext = context;
+ }
registerIntentFilter();
}
+
+
public static void getLeScanCallback() {
caLeRegisterLeScanCallback(mLeScanCallback);
}
private CaNfcInterface(Context context, Activity activity) {
Log.d(MYTAG, "NFC registerNfcReceiver");
- mContext = context;
+ synchronized(CaNfcInterface.class) {
+ mContext = context;
+ }
mActivity = activity;
mAdapter = NfcAdapter.getDefaultAdapter(mContext);
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+ <classpathentry kind="src" path="src"/>\r
+ <classpathentry kind="src" path="gen"/>\r
+ <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>\r
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>\r
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>\r
+ <classpathentry kind="output" path="bin/classes"/>\r
+</classpath>\r
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+ <name>Iot</name>\r
+ <comment></comment>\r
+ <projects>\r
+ </projects>\r
+ <buildSpec>\r
+ <buildCommand>\r
+ <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>\r
+ <arguments>\r
+ </arguments>\r
+ </buildCommand>\r
+ <buildCommand>\r
+ <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>\r
+ <arguments>\r
+ </arguments>\r
+ </buildCommand>\r
+ <buildCommand>\r
+ <name>org.eclipse.jdt.core.javabuilder</name>\r
+ <arguments>\r
+ </arguments>\r
+ </buildCommand>\r
+ <buildCommand>\r
+ <name>com.android.ide.eclipse.adt.ApkBuilder</name>\r
+ <arguments>\r
+ </arguments>\r
+ </buildCommand>\r
+ </buildSpec>\r
+ <natures>\r
+ <nature>com.android.ide.eclipse.adt.AndroidNature</nature>\r
+ <nature>org.eclipse.jdt.core.javanature</nature>\r
+ </natures>\r
+</projectDescription>\r
--- /dev/null
+<?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>
--- /dev/null
+apply plugin: 'com.android.application'\r
+\r
+android {\r
+ compileSdkVersion 21\r
+ buildToolsVersion "20.0.0"\r
+\r
+ defaultConfig {\r
+ applicationId "org.iotivity.base.examples.DirectPairing"\r
+ minSdkVersion 21\r
+ targetSdkVersion 21\r
+ versionCode 1\r
+ versionName "1.0"\r
+ }\r
+ buildTypes {\r
+ release {\r
+ minifyEnabled false\r
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+ }\r
+ }\r
+ lintOptions {\r
+ abortOnError false\r
+ }\r
+}\r
+repositories {\r
+ flatDir {\r
+ dirs "../../android_api/base/build/outputs/aar/"\r
+ }\r
+}\r
+\r
+try {\r
+ dependencies {\r
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"\r
+ }\r
+} catch (all) {\r
+ print "${ERROR_MSG}"\r
+ assert all\r
+}\r
+\r
--- /dev/null
+# 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
--- /dev/null
+<?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>
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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;
+ }
+
+}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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;
+ }
+}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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());
+ }
+ }
+ }
+
+ }
+}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // 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;
+}
--- /dev/null
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+ xmlns:tools="http://schemas.android.com/tools"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="match_parent"\r
+ android:orientation="vertical"\r
+ android:paddingBottom="@dimen/activity_vertical_margin"\r
+ android:paddingLeft="@dimen/activity_horizontal_margin"\r
+ android:paddingRight="@dimen/activity_horizontal_margin"\r
+ android:paddingTop="@dimen/activity_vertical_margin"\r
+ tools:context="com.example.iot.MainActivity" >\r
+\r
+ <LinearLayout\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:weightSum="1" >\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:layout_weight="0.75"\r
+ android:gravity="center"\r
+ android:text="@string/discover_items"\r
+ android:textSize="18sp" />\r
+\r
+ <Switch\r
+ android:id="@+id/discover"\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:layout_weight="0.25" />\r
+ </LinearLayout>\r
+\r
+ <View\r
+ android:layout_width="match_parent"\r
+ android:layout_height="2dp"\r
+ android:background="#13AEF4" />\r
+\r
+ <ListView\r
+ android:id="@+id/list_view"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="250dp" />\r
+\r
+ <View\r
+ android:layout_width="match_parent"\r
+ android:layout_height="2dp"\r
+ android:background="#13AEF4" />\r
+\r
+ <RelativeLayout\r
+ android:id="@+id/relLay"\r
+ android:layout_width="fill_parent"\r
+ android:layout_height="wrap_content"\r
+ android:orientation="horizontal"\r
+ android:padding="15dp" >\r
+\r
+ <Button\r
+ android:id="@+id/saveDiscovered"\r
+ android:layout_width="90dp"\r
+ android:layout_height="30dp"\r
+ android:layout_centerInParent="true"\r
+ android:background="#13AEF4"\r
+ android:text="Save"\r
+ android:textColor="#FFFFFF" />\r
+ </RelativeLayout>\r
+\r
+ <View\r
+ android:layout_width="match_parent"\r
+ android:layout_height="2dp"\r
+ android:background="#13AEF4" />\r
+\r
+ <TextView\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:layout_gravity="center_vertical"\r
+ android:paddingLeft="50dp"\r
+ android:text="@string/paired_list"\r
+ android:textSize="18sp" />\r
+\r
+ <View\r
+ android:layout_width="match_parent"\r
+ android:layout_height="2dp"\r
+ android:background="#13AEF4" />\r
+\r
+ <ExpandableListView\r
+ android:id="@+id/list_view_paired_list"\r
+ android:layout_width="fill_parent"\r
+ android:layout_height="200dp"\r
+ android:paddingTop="5dp"\r
+ android:groupIndicator="@null" >\r
+ </ExpandableListView>\r
+\r
+ <View\r
+ android:layout_width="match_parent"\r
+ android:layout_height="2dp"\r
+ android:background="#13AEF4" />\r
+\r
+</LinearLayout>
\ No newline at end of file
--- /dev/null
+<?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
--- /dev/null
+<selector xmlns:android="http://schemas.android.com/apk/res/android">\r
+Â <item android:drawable="@drawable/arrow_right" android:state_empty="true"></item>\r
+Â Â Â Â <item android:drawable="@drawable/arrow_down" android:state_expanded="true"></item>\r
+Â Â Â Â <item android:drawable="@drawable/arrow_right"></item>\r
+\r
+</selector>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>\r
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+ android:layout_width="fill_parent"\r
+ android:layout_height="40dp"\r
+ android:background="#ffffff"\r
+ android:orientation="horizontal" >\r
+\r
+ <TextView\r
+ android:id="@+id/title"\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="40dp"\r
+ android:layout_weight="0.9"\r
+ android:gravity="center_vertical"\r
+ android:paddingLeft="40dp"\r
+ android:text="Items"\r
+ android:textColor="#040404"\r
+ android:textSize="16sp"\r
+ android:textStyle="bold"\r
+ android:typeface="sans" />\r
+\r
+ <ImageView\r
+ android:id="@+id/image"\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="20dp"\r
+ android:layout_gravity="center_vertical"\r
+ android:layout_weight="0.1" />\r
+\r
+</LinearLayout>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>\r
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+ android:layout_width="fill_parent"\r
+ android:layout_height="wrap_content"\r
+ android:orientation="vertical" >\r
+\r
+ <TextView\r
+ android:id="@+id/textViewItem"\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:gravity="center_vertical"\r
+ android:paddingLeft="50dp"\r
+ android:text="Paired Items"\r
+ android:textColor="#545454"\r
+ android:textSize="15sp" />\r
+\r
+ <TextView\r
+ android:id="@+id/textViewSource"\r
+ android:layout_below="@id/textViewItem"\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:gravity="center_vertical"\r
+ android:paddingLeft="50dp"\r
+ android:text="Paired Source"\r
+ android:textColor="#545454"\r
+ android:textSize="15sp" />\r
+\r
+ <TextView\r
+ android:id="@+id/textViewStatus"\r
+ android:layout_below="@id/textViewSource"\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:gravity="center_vertical"\r
+ android:paddingLeft="50dp"\r
+ android:text="Paired Status"\r
+ android:textColor="#545454"\r
+ android:textSize="15sp" />\r
+\r
+</RelativeLayout>
\ No newline at end of file
--- /dev/null
+<menu xmlns:android="http://schemas.android.com/apk/res/android"\r
+ xmlns:app="http://schemas.android.com/apk/res-auto"\r
+ xmlns:tools="http://schemas.android.com/tools"\r
+ tools:context="org.iotivity.base.examples.MainActivity" >\r
+\r
+ <item\r
+ android:id="@+id/action_settings"\r
+ android:orderInCategory="100"\r
+ android:title="@string/action_settings"/>\r
+\r
+</menu>\r
--- /dev/null
+<resources>\r
+\r
+ <!--\r
+ Base application theme for API 11+. This theme completely replaces
+ AppBaseTheme from res/values/styles.xml on API 11+ devices.\r
+ -->\r
+ <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">\r
+ <!-- API 11 theme customizations can go here. -->\r
+ </style>\r
+\r
+</resources>\r
--- /dev/null
+<resources>\r
+\r
+ <!--\r
+ Base application theme for API 14+. This theme completely replaces
+ AppBaseTheme from BOTH res/values/styles.xml and
+ res/values-v11/styles.xml on API 14+ devices.\r
+ -->\r
+ <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">\r
+ <!-- API 14 theme customizations can go here. -->\r
+ </style>\r
+\r
+</resources>\r
--- /dev/null
+<resources>\r
+\r
+ <!--\r
+ Example customization of dimensions originally defined in res/values/dimens.xml
+ (such as screen margins) for screens with more than 820dp of available width. This
+ would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).\r
+ -->\r
+ <dimen name="activity_horizontal_margin">64dp</dimen>\r
+\r
+</resources>\r
--- /dev/null
+<resources>\r
+\r
+ <!-- Default screen margins, per the Android Design guidelines. -->\r
+ <dimen name="activity_horizontal_margin">16dp</dimen>\r
+ <dimen name="activity_vertical_margin">16dp</dimen>\r
+\r
+</resources>\r
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>\r
+\r
+ <string name="app_name">DirectPairingClient</string>\r
+ <string name="discover_items">Discover Resources</string>
+ <string name="paired_items">Paired Resources</string>
+ <string name="paired_list">Direct Paired Resources</string>\r
+ <string name="action_settings">Settings</string>\r
+\r
+</resources>\r
--- /dev/null
+<resources>\r
+\r
+ <!--\r
+ Base application theme, dependent on API level. This theme is replaced
+ by AppBaseTheme from res/values-vXX/styles.xml on newer devices.\r
+ -->\r
+ <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">\r
+ <!--\r
+ Theme customizations available in newer API levels can go in
+ res/values-vXX/styles.xml, while customizations related to
+ backward-compatibility can go here.\r
+ -->\r
+ </style>\r
+\r
+ <!-- Application theme. -->\r
+ <style name="AppTheme" parent="AppBaseTheme">\r
+ <!-- All customizations that are NOT specific to a particular API-level can go here. -->\r
+ </style>\r
+\r
+</resources>\r
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: ");
}};
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.");
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.
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);
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
},\r
{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/ad",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.ad"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/amacl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.amacl"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } \r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
+ }\r
],\r
"permission": 2\r
}\r
]\r
},\r
"rowneruuid" : "61646D69-6E44-6576-6963-655575696430"\r
- }, \r
+ },\r
"pstat": {\r
"isop": true,\r
"cm": 2,\r
"sct": 1,\r
"owned": true,\r
"deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
- "dpc": false,\r
+ "x.com.samsung.dpc": false,\r
"devowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
"rowneruuid": "61646D69-6E44-6576-6963-655575696430"\r
}\r
import org.iotivity.base.OcProvisioning;
import org.iotivity.base.OcSecureResource;
import org.iotivity.base.OicSecAcl;
+import org.iotivity.base.OicSecPdAcl;
+import org.iotivity.base.OcPrmType;
import org.iotivity.base.OxmType;
import org.iotivity.base.PlatformConfig;
import org.iotivity.base.ProvisionResult;
private List<OcSecureResource> deviceList;
private List<OcSecureResource> ownedDeviceList;
private TextView mEventsTextView;
+
+ OcSecureResource.ProvisionDirectPairingListener provisionDPListener =
+ new OcSecureResource.ProvisionDirectPairingListener() {
+ @Override
+ public void provisionDirectPairingListener(List<ProvisionResult> provisionResults,
+ int hasError) {
+ Log.d(TAG, "Inside provisionDPListener");
+ ProvisionResult pResult = provisionResults.get(0);
+ if (hasError == StringConstants.ERROR_CODE) {
+ logMessage(TAG + "Provision direct pairing Failed for " + pResult.getDevId());
+ } else {
+ logMessage(TAG + "Provision direct pairing Successful for " + pResult.getDevId());
+ }
+ }
+ };
+
OcSecureResource.ProvisionAclListener provisionAclListener =
new OcSecureResource.ProvisionAclListener() {
@Override
mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
layout.addView(mEventsTextView, new LinearLayout.LayoutParams(
- LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+ LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
);
filePath = getFilesDir().getPath() + "/"; // data/data/<package>/files/
//copy CBOR file when application runs first time
}
}
+
+ 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()
if (ownedDeviceList.size() > 0) {
for (int i = 0; i < ownedDeviceList.size(); i++) {
publishProgress(TAG + "Owned Discovered Device " + (i + 1) + "= " +
- ownedDeviceList.get(i).getDeviceID()
- + "\nIP Address= " + ownedDeviceList.get(i).getIpAddr()
- + "\nOwned Status= " + ownedDeviceList.get(i).getOwnedStatus()
- + "\nDevice Status= " + ((ownedDeviceList.get(i).
- getDeviceStatus() == DeviceStatus.ON) ? "ON" : "OFF")
+ ownedDeviceList.get(i).getDeviceID()
+ + "\nIP Address= " + ownedDeviceList.get(i).getIpAddr()
+ + "\nOwned Status= " + ownedDeviceList.get(i).getOwnedStatus()
+ + "\nDevice Status= " + ((ownedDeviceList.get(i).
+ getDeviceStatus() == DeviceStatus.ON) ? "ON" : "OFF")
);
}
} else {
@Override
protected void onPostExecute(String s) {
+
+
+ if (ownedDeviceList.size() > 0 && "success".equals(s)) {
+ doDPProvisioning();
+ }
+
if (ownedDeviceList.size() > 1 && "success".equals(s)) {
doPairwiseProvisioning();
}
include ':simpleserver', ':simpleclient', ':fridgeserver', ':fridgeclient', ':guiclient', ':presenceserver', ':presenceclient', ':devicediscoveryclient', ':devicediscoveryserver', ':groupclient', ':groupserver', ':fridgegroupclient', ':fridgegroupserver', ':simplebase'
SECURED=System.getProperty('SECURE')
if(SECURED== "1"){
- include ':provisioningclient'
+ include ':provisioningclient', ':DirectPairing'
}
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
},\r
{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/ad",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.ad"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
- "href": "/oic/sec/acl",\r
+ "href": "/oic/sec/amacl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.amacl"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } ,\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
"deviceuuid": "32323232-3232-3232-3232-323232323232",\r
"devowneruuid": "32323232-3232-3232-3232-323232323232",\r
"rowneruuid": "32323232-3232-3232-3232-323232323232",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
},\r
"cred": {\r
"creds": [\r
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
},\r
{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/ad",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.ad"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } ,\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/a/light",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.core"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/a/light0",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.core"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/a/light1",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.core"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 6\r
"deviceuuid": "31313131-3131-3131-3131-313131313131",\r
"devowneruuid": "32323232-3232-3232-3232-323232323232",\r
"rowneruuid": "31313131-3131-3131-3131-313131313131",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
},\r
"cred": {\r
"creds": [\r
# Map of host os and allowed target os (host: allowed target os)
host_target_map = {
'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
- 'windows': ['windows', 'winrt', 'android', 'arduino'],
+ 'windows': ['windows', 'android', 'arduino'],
'darwin': ['darwin', 'ios', 'android', 'arduino'],
+ 'msys_nt' :['msys_nt'],
}
# Map of os and allowed archs (os: allowed archs)
os_arch_map = {
- 'linux': ['x86', 'x86_64', 'arm', 'arm64'],
- 'tizen': ['x86', 'x86_64', 'arm', 'arm64', 'armeabi-v7a'],
+ 'linux': ['x86', 'x86_64', 'arm', 'arm-v7a', 'arm64'],
+ 'tizen': ['x86', 'x86_64', 'arm', 'arm-v7a', 'armeabi-v7a', 'arm64'],
'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
'windows': ['x86', 'amd64', 'arm'],
- 'winrt': ['arm'],
+ 'msys_nt':['x86', 'x86_64'],
'darwin': ['i386', 'x86_64'],
'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
'arduino': ['avr', 'arm'],
host = platform.system().lower()
+# the host string contains version of windows. 6.3, 6.4, 10.0 which is 8.0, 8.1, and 10 respectively.
+# Let's canonicalize the msys_nt-XX.X system name by stripping version off.
+if 'msys_nt' in host:
+ host = 'msys_nt'
+
if not host_target_map.has_key(host):
print "\nError: Current system (%s) isn't supported\n" % host
Exit(1)
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)
else:
i_n = ienv.Install(user_prefix + '/lib', targets)
ienv.Alias("install", i_n)
+ else:
+ i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+ ienv.Alias("install", i_n)
def __installbin(ienv, targets, name):
user_prefix = env.get('PREFIX')
user_prefix = env.get('PREFIX')
if user_prefix:
i_n = ienv.Install(user_prefix + '/include/' + dir ,targets)
- ienv.Alias("install", i_n)
+ else:
+ i_n = ienv.Install(os.path.join(env.get('BUILD_DIR'), 'include', dir), targets)
+ ienv.Alias("install", i_n)
def __installpcfile(ienv, targets, name):
user_prefix = env.get('PREFIX')
i_n = ienv.Install(user_lib + '/pkgconfig', targets)
else:
i_n = ienv.Install(user_prefix + '/lib/pkgconfig', targets)
- ienv.Alias("install", i_n)
+ else:
+ i_n = ienv.Install(env.get('BUILD_DIR') + 'lib/pkgconfig', targets)
+ ienv.Alias("install", i_n)
def __append_target(ienv, name, targets = None):
if targets:
if user_prefix:
pc_vars = {'\@PREFIX\@': user_prefix,
'\@EXEC_PREFIX\@':user_prefix,
- '\@VERSION\@': '1.0.1',
+ '\@VERSION\@': '1.1.1',
'\@LIB_INSTALL_DIR\@': user_lib,
'\@ROUTING_DEFINE\@': routing_define
}
else:
- pc_vars = {'\@PREFIX\@': env.get('BUILD_DIR'),
- '\@EXEC_PREFIX\@': env.get('BUILD_DIR'),
- '\@VERSION\@': '1.0.1',
+ pc_vars = {'\@PREFIX\@': env.get('BUILD_DIR').encode('string_escape'),
+ '\@EXEC_PREFIX\@': env.get('BUILD_DIR').encode('string_escape'),
+ '\@VERSION\@': '1.1.1',
'\@LIB_INSTALL_DIR\@': user_lib,
'\@ROUTING_DEFINE\@': routing_define
}
# POSIX_SUPPORTED, 1 if it is supported, 0 otherwise
conf.CheckPThreadsSupport()
+######################################################################
+# Generate macros for presence of headers
+######################################################################
+cxx_headers = ['arpa/inet.h',
+ 'fcntl.h',
+ 'grp.h',
+ 'in6addr.h',
+ 'linux/limits.h',
+ 'memory.h',
+ 'netdb.h',
+ 'netinet/in.h',
+ 'pthread.h',
+ 'pwd.h',
+ 'stdlib.h',
+ 'string.h',
+ 'strings.h',
+ 'sys/socket.h',
+ 'sys/stat.h',
+ 'sys/time.h',
+ 'sys/timeb.h',
+ 'sys/types.h',
+ 'sys/unistd.h',
+ 'syslog.h',
+ 'time.h',
+ 'unistd.h',
+ 'uuid/uuid.h',
+ 'windows.h',
+ 'winsock2.h',
+ 'ws2tcpip.h']
+
+if target_os == 'arduino':
+ # Detection of headers on the Arduino platform is currently broken.
+ cxx_headers = []
+
+if target_os == 'msys_nt':
+ # WinPThread provides a pthread.h, but we want to use native threads.
+ cxx_headers.remove('pthread.h')
+
+def get_define_from_header_file(header_file):
+ header_file_converted = header_file.replace("/","_").replace(".","_").upper()
+ return "HAVE_" + header_file_converted
+
+for header_file_name in cxx_headers:
+ if conf.CheckCXXHeader(header_file_name):
+ conf.env.AppendUnique(CPPDEFINES = [get_define_from_header_file(header_file_name)])
+
env = conf.Finish()
######################################################################
else:
env.AppendUnique(CCFLAGS = ['-g'])
+# Force header presence defines
+env.AppendUnique(CPPDEFINES = ['HAVE_ARDUINO_TIME_H'])
+
# BOARD / CPU option
# Get IDE version
# External library include files are in <src_dir>/deps/<target_os>/include
# the library binaries are in <src_dir>/deps/<target_os>/lib/<arch>
-env.AppendUnique(CPPPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'include')])
-env.AppendUnique(LIBPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'lib', target_arch)])
+if target_os not in ['windows']:
+ env.AppendUnique(CPPPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'include')])
+ env.AppendUnique(LIBPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'lib', target_arch)])
# Check whether a library exists, if not, notify user to install it or try to
# download the source code and build it
--- /dev/null
+##
+# This script sets compiler flags for
+# MinGW in the MSYS environment.
+##
+Import('env')
+
+# Set common flags
+# Overwrite suffixes and prefixes
+if env['TARGET_OS'] == 'msys_nt':
+ env['SHLIBPREFIX'] = 'lib'
+
+env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+
+target_arch = env.get('TARGET_ARCH')
+
+if env['CC'] == 'gcc':
+ if env.get('RELEASE'):
+ env.AppendUnique(CCFLAGS = ['-Os'])
+ env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+ else:
+ env.AppendUnique(CCFLAGS = ['-g'])
+ env.AppendUnique(CFLAGS = ['-std=c99'])
+ env.AppendUnique(CXXFLAGS = ['-std=c++11'])
+ env.AppendUnique(CCFLAGS = ['-Wall', '-Wextra', '-Wa,-mbig-obj'])
+ env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '_GNU_SOURCE', '__msys_nt__', '_WIN32_WINNT=0x0600'])
+
+ # Set arch flags
+ if target_arch in ['x86']:
+ env.AppendUnique(CCFLAGS = ['-m32'])
+ env.AppendUnique(LINKFLAGS = ['-m32'])
+ elif target_arch in ['x86_64']:
+ env.AppendUnique(CCFLAGS = ['-m64'])
+ env.AppendUnique(LINKFLAGS = ['-m64'])
# read tools for Windows system
if env["PLATFORM"] <> "darwin" and "win" in env["PLATFORM"] :
- if env.WhereIs("7z") :
+ if env.WhereIs('7z', env.get('PATH')):
toolset["EXTRACTOR"]["TARGZ"]["RUN"] = "7z"
toolset["EXTRACTOR"]["TARGZ"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
toolset["EXTRACTOR"]["TARGZ"]["LISTFLAGS"] = "x"
toolset["EXTRACTOR"]["TARGZ"]["LISTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} l -sii -ttar -y -so"
toolset["EXTRACTOR"]["TARGZ"]["EXTRACTFLAGS"] = "x"
- toolset["EXTRACTOR"]["TARGZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -oc:${UNPACK['EXTRACTDIR']}"
+ toolset["EXTRACTOR"]["TARGZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -o${UNPACK['EXTRACTDIR']}"
toolset["EXTRACTOR"]["TARBZ"]["RUN"] = "7z"
toolset["EXTRACTOR"]["TARBZ"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
toolset["EXTRACTOR"]["TARBZ"]["LISTFLAGS"] = "x"
toolset["EXTRACTOR"]["TARBZ"]["LISTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} l -sii -ttar -y -so"
toolset["EXTRACTOR"]["TARBZ"]["EXTRACTFLAGS"] = "x"
- toolset["EXTRACTOR"]["TARBZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -oc:${UNPACK['EXTRACTDIR']}"
+ toolset["EXTRACTOR"]["TARBZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -o${UNPACK['EXTRACTDIR']}"
toolset["EXTRACTOR"]["BZIP"]["RUN"] = "7z"
toolset["EXTRACTOR"]["BZIP"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
toolset["EXTRACTOR"]["BZIP"]["LISTFLAGS"] = "l"
toolset["EXTRACTOR"]["BZIP"]["LISTSUFFIX"] = "-y -so"
toolset["EXTRACTOR"]["BZIP"]["EXTRACTFLAGS"] = "x"
- toolset["EXTRACTOR"]["BZIP"]["EXTRACTSUFFIX"] = "-y -oc:${UNPACK['EXTRACTDIR']}"
+ toolset["EXTRACTOR"]["BZIP"]["EXTRACTSUFFIX"] = "-y -o${UNPACK['EXTRACTDIR']}"
toolset["EXTRACTOR"]["GZIP"]["RUN"] = "7z"
toolset["EXTRACTOR"]["GZIP"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
toolset["EXTRACTOR"]["GZIP"]["LISTFLAGS"] = "l"
toolset["EXTRACTOR"]["GZIP"]["LISTSUFFIX"] = "-y -so"
toolset["EXTRACTOR"]["GZIP"]["EXTRACTFLAGS"] = "x"
- toolset["EXTRACTOR"]["GZIP"]["EXTRACTSUFFIX"] = "-y -oc:${UNPACK['EXTRACTDIR']}"
+ toolset["EXTRACTOR"]["GZIP"]["EXTRACTSUFFIX"] = "-y -o${UNPACK['EXTRACTDIR']}"
toolset["EXTRACTOR"]["ZIP"]["RUN"] = "7z"
toolset["EXTRACTOR"]["ZIP"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
toolset["EXTRACTOR"]["ZIP"]["LISTFLAGS"] = "l"
toolset["EXTRACTOR"]["ZIP"]["LISTSUFFIX"] = "-y -so"
toolset["EXTRACTOR"]["ZIP"]["EXTRACTFLAGS"] = "x"
- toolset["EXTRACTOR"]["ZIP"]["EXTRACTSUFFIX"] = "-y -oc:${UNPACK['EXTRACTDIR']}"
+ toolset["EXTRACTOR"]["ZIP"]["EXTRACTSUFFIX"] = "-y -o${UNPACK['EXTRACTDIR']}"
toolset["EXTRACTOR"]["TAR"]["RUN"] = "7z"
toolset["EXTRACTOR"]["TAR"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
toolset["EXTRACTOR"]["TAR"]["LISTFLAGS"] = "l"
toolset["EXTRACTOR"]["TAR"]["LISTSUFFIX"] = "-y -ttar -so"
toolset["EXTRACTOR"]["TAR"]["EXTRACTFLAGS"] = "x"
- toolset["EXTRACTOR"]["TAR"]["EXTRACTSUFFIX"] = "-y -ttar -oc:${UNPACK['EXTRACTDIR']}"
+ toolset["EXTRACTOR"]["TAR"]["EXTRACTSUFFIX"] = "-y -ttar -o${UNPACK['EXTRACTDIR']}"
+ else:
+ print '''*********************** Error ************************
+* *
+* Please make sure that 7-zip is in your System PATH *
+* *
+******************************************************
+'''
# here can add some other Windows tools, that can handle the archive files
# but I don't know which ones can handle all file types
# read the tools on *nix systems and sets the default parameters
- elif env["PLATFORM"] in ["darwin", "linux", "posix"] :
+ elif env["PLATFORM"] in ["darwin", "linux", "posix", "msys"] :
if env.WhereIs("unzip") :
toolset["EXTRACTOR"]["ZIP"]["RUN"] = "unzip"
# This script includes windows specific config (MSVS/MSVC)
##
Import('env')
+import os.path
# Set common flags
-env.AppendUnique(CXXFLAGS=['/wd4244', '/wd4267','/wd4345', '/wd4355', '/wd4800', '/wd4996'])
-env.AppendUnique(CCFLAGS=['/EHsc'])
+if env['CC'] == 'cl':
+
+ # TODO: re-enable warnings, especially: 4244, 4267, 4365
+ env.AppendUnique(CXXFLAGS=[
+ '/wd4244', # C4244 conversion from one type to another type results in a possible loss of data.
+ '/wd4267', # C4267 conversion from size_t to a smaller type.
+ '/wd4355', # C4355 'this' used in base member initializer list.
+ '/wd4800', # C4800 forcing value to bool 'true' or 'false'.
+ '/wd4996', # C4996 deprecated declaration.
+ '/wd4820', # C4820 added padding to the end of a struct.
+ '/wd4514', # C4514 unreferenced inline function has been removed
+ '/wd4365', # C4365 signed/unsigned mismatch
+ '/wd4503']) # C4503 decorated name length exceeded, name was truncated
+
+ env.AppendUnique(CCFLAGS=['/EHsc'])
+
+ vs_version = env['MSVC_VERSION']
+
+ # Enable special exports for unit test purposes
+ if env.get('TEST') == '1':
+ env.AppendUnique(CPPDEFINES = ['ENABLE_TEST_EXPORTS'])
+ # Set release/debug flags
+ if env.get('RELEASE'):
+ env.AppendUnique(CCFLAGS = ['/MD', '/O2', '/GF'])
+ env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+ elif env.get('TARGET_ARCH') in ['x86', 'x86_64'] or "14.0" in vs_version:
+ env.AppendUnique(CCFLAGS = ['/MDd', '/Od', '/ZI', '/RTC1', '/Gm'])
+ env.AppendUnique(LINKFLAGS = ['/debug'])
+ else:
+ env.AppendUnique(CCFLAGS = ['/MDd', '/Od', '/Zi', '/RTC1', '/Gm'])
+ env.AppendUnique(LINKFLAGS = ['/debug'])
+ env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+ env.AppendUnique(PATH = os.environ['PATH'])
+
+elif env['CC'] == 'gcc':
+ print "\nError: gcc not supported on Windows. Use Visual Studio!\n"
+ Exit(1);
-# Set release/debug flags
-if env.get('RELEASE'):
- env.AppendUnique(CCFLAGS = ['/MD', '/O2', '/GF'])
- env.AppendUnique(CPPDEFINES = ['NDEBUG'])
-else:
- env.AppendUnique(CCFLAGS = ['/MDd', '/Od', '/ZI', '/GZ', '/Gm'])
- env.AppendUnique(CPPDEFINES = ['_DEBUG'])
- env.AppendUnique(LINKFLAGS = ['/debug'])
])
target_os = env.get('TARGET_OS')
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
examples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
# Note: 'pthread' is in libc for android. On other platform, if use
WrapRequest *m_typeRequest;
};
-struct WrapRequest
+class WrapRequest
{
+public:
WrapRequest(WrapResource *wres, RequestType type, token_t token);
friend class WrapResource;
target_os = env.get('TARGET_OS')
target_arch = env.get('TARGET_ARCH')
+src_dir = env.get('SRC_DIR')
+
+boost_version = '1.60.0'
+
+# TODO: Remove coupling between build scripts and 1_58_0 version for Android
+if target_os in ['android']:
+ boost_version = '1.58.0'
+
+boost_base_name = 'boost_'+string.replace(boost_version,'.','_')
+boost_arch_name = boost_base_name+'.zip'
+boost_b2_name = boost_base_name+os.sep+'b2'
+boost_url = 'http://downloads.sourceforge.net/project/boost/boost/'+boost_version+'/'+boost_arch_name+'?r=&ts=1421801329&use_mirror=iweb'
+
+boost_dir = os.path.join(src_dir,'extlibs','boost','boost')
+boost_bootstrap = os.path.join(boost_dir,'bootstrap.bat')
if 'linux' == target_os :
# Check for Boost libraries in /usr/boost
print 'TODO: Perform platform check for linux'
raise SCons.Errors.EnvironmentError('Unsupported platform')
-if 'android' == target_os :
+elif target_os in ['windows']:
+ boost_zip_file = os.path.join(src_dir,'extlibs','boost',boost_arch_name)
+
+ if not os.path.exists(boost_bootstrap):
+
+ # Download if necessary
+ if os.path.exists(boost_zip_file):
+ boost_zip = boost_zip_file
+ else:
+ print '*** Downloading Boost zip file (> 100MB). Please wait... ***'
+ boost_zip = env.Download(boost_zip_file, boost_url)
+
+ # Unzip boost
+ print '*** Unpacking boost %s zip file ... ***' % boost_version
+ env.UnpackAll(boost_dir, boost_zip)
+
+ # Rename from boost_1_60_0 -> boost
+ os.rename(boost_base_name, 'boost')
+
+ # Sanity check, in case the above method didn't work
+ if not os.path.exists(boost_bootstrap):
+ print '''
+*********************************** Error: ****************************************
+* Please download boost from the following website:
+*
+* ''' + boost_url + '''
+*
+* and extract the contents directly into
+*
+* ''' + boost_dir + '''
+*
+* such that this build system can find:
+*
+* ''' + boost_bootstrap + '''
+*
+***********************************************************************************
+'''
+ Exit(1)
+
+elif target_os in ['android']:
env.Tool('URLDownload', toolpath=['../../tools/scons'])
env.Tool('UnpackAll', toolpath=['../../tools/scons'])
env.Tool('BoostBootstrap', toolpath=['../../tools/scons'])
env.Tool('BoostBuild', toolpath=['../../tools/scons'])
- boost_version = '1.58.0'
- boost_base_name = 'boost_'+string.replace(boost_version,'.','_')
- boost_arch_name = boost_base_name+'.zip'
- boost_b2_name = boost_base_name+os.sep+'b2'
- boost_url = 'http://downloads.sourceforge.net/project/boost/boost/'+boost_version+'/'+boost_arch_name+'?r=&ts=1421801329&use_mirror=iweb'
-
host_os = sys.platform
if host_os == 'linux2' :
#define cJSON_IsReference 256
+#include <platform_features.h>
+
/* The cJSON structure: */
typedef struct cJSON {
struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
} cJSON_Hooks;
/* Supply malloc, realloc and free functions to cJSON */
-extern void cJSON_InitHooks(cJSON_Hooks* hooks);
+OC_EXPORT extern void cJSON_InitHooks(cJSON_Hooks* hooks);
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
-extern cJSON *cJSON_Parse(const char *value);
+OC_EXPORT extern cJSON *cJSON_Parse(const char *value);
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
-extern char *cJSON_Print(cJSON *item);
+OC_EXPORT extern char *cJSON_Print(cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
-extern char *cJSON_PrintUnformatted(cJSON *item);
+OC_EXPORT extern char *cJSON_PrintUnformatted(cJSON *item);
/* Delete a cJSON entity and all subentities. */
-extern void cJSON_Delete(cJSON *c);
+OC_EXPORT extern void cJSON_Delete(cJSON *c);
/* Returns the number of items in an array (or object). */
-extern int cJSON_GetArraySize(cJSON *array);
+OC_EXPORT extern int cJSON_GetArraySize(cJSON *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
-extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
+OC_EXPORT extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
/* Get item "string" from object. Case insensitive. */
-extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
+OC_EXPORT extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
-extern const char *cJSON_GetErrorPtr(void);
-
+OC_EXPORT extern const char *cJSON_GetErrorPtr(void);
+
/* These calls create a cJSON item of the appropriate type. */
-extern cJSON *cJSON_CreateNull(void);
-extern cJSON *cJSON_CreateTrue(void);
-extern cJSON *cJSON_CreateFalse(void);
-extern cJSON *cJSON_CreateBool(int b);
-extern cJSON *cJSON_CreateNumber(double num);
-extern cJSON *cJSON_CreateString(const char *string);
-extern cJSON *cJSON_CreateArray(void);
-extern cJSON *cJSON_CreateObject(void);
+OC_EXPORT extern cJSON *cJSON_CreateNull(void);
+OC_EXPORT extern cJSON *cJSON_CreateTrue(void);
+OC_EXPORT extern cJSON *cJSON_CreateFalse(void);
+OC_EXPORT extern cJSON *cJSON_CreateBool(int b);
+OC_EXPORT extern cJSON *cJSON_CreateNumber(double num);
+OC_EXPORT extern cJSON *cJSON_CreateString(const char *string);
+OC_EXPORT extern cJSON *cJSON_CreateArray(void);
+OC_EXPORT extern cJSON *cJSON_CreateObject(void);
/* These utilities create an Array of count items. */
-extern cJSON *cJSON_CreateIntArray(const int *numbers,int count);
-extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count);
-extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count);
-extern cJSON *cJSON_CreateStringArray(const char **strings,int count);
+OC_EXPORT extern cJSON *cJSON_CreateIntArray(const int *numbers,int count);
+OC_EXPORT extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count);
+OC_EXPORT extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count);
+OC_EXPORT extern cJSON *cJSON_CreateStringArray(const char **strings,int count);
/* Append item to the specified array/object. */
-extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
-extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
+OC_EXPORT extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
+OC_EXPORT extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
-extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
-extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item);
+OC_EXPORT extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
+OC_EXPORT extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item);
/* Remove/Detatch items from Arrays/Objects. */
-extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which);
-extern void cJSON_DeleteItemFromArray(cJSON *array,int which);
-extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string);
-extern void cJSON_DeleteItemFromObject(cJSON *object,const char *string);
-
+OC_EXPORT extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which);
+OC_EXPORT extern void cJSON_DeleteItemFromArray(cJSON *array,int which);
+OC_EXPORT extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string);
+OC_EXPORT extern void cJSON_DeleteItemFromObject(cJSON *object,const char *string);
+
/* Update array items. */
-extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem);
-extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
+OC_EXPORT extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem);
+OC_EXPORT extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
/* Duplicate a cJSON item */
-extern cJSON *cJSON_Duplicate(cJSON *item,int recurse);
+OC_EXPORT extern cJSON *cJSON_Duplicate(cJSON *item,int recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
need to be released. With recurse!=0, it will duplicate any children connected to the item.
The item->next and ->prev pointers are always zero on return from Duplicate. */
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
-extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated);
+OC_EXPORT extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated);
-extern void cJSON_Minify(char *json);
+OC_EXPORT extern void cJSON_Minify(char *json);
/* Macros for creating things quickly. */
#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull())
target_os = env.get('TARGET_OS')
src_dir = env.get('SRC_DIR')
-targets_need_gtest = ['darwin','linux']
-gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0'
-gtest_zip_file = src_dir + '/extlibs/gtest/gtest-1.7.0.zip'
+targets_need_gtest = ['darwin','linux', 'msys_nt', 'windows']
+gtest_dir = os.path.join(src_dir, 'extlibs', 'gtest', 'gtest-1.7.0')
+gtest_zip_file = os.path.join(src_dir, 'extlibs', 'gtest', 'gtest-1.7.0.zip')
gtest_url = 'https://googletest.googlecode.com/files/gtest-1.7.0.zip'
if target_os in targets_need_gtest:
print '*** Checking for installation of google unit test 1.7.0 ***'
-
if not os.path.exists(gtest_dir):
# If the gtest zip file is not already present, download it
if not os.path.exists(gtest_zip_file):
gtest_zip = gtest_zip_file
# Unzip gtest
- print 'Unzipping google unit test'
- env.UnpackAll(gtest_dir, gtest_zip)
+ if not os.path.exists(os.path.join(gtest_dir, 'configure')):
+ print 'Unzipping google unit test'
+ env.UnpackAll(gtest_dir, gtest_zip)
if target_os == 'darwin':
# Run configure on gtest
print 'Configuring google unit test'
if env.get('CROSS_COMPILE'):
- env.Configure(gtest_dir, './configure --host=' + env['CROSS_COMPILE'])
+ env.Configure(gtest_dir, './configure --disable-shared --host=' + env['CROSS_COMPILE'])
else:
- env.Configure(gtest_dir, './configure')
+ env.Configure(gtest_dir, './configure --disable-shared')
+ # Run make on gtest
+ print 'Making google unit test'
+ env.Configure(gtest_dir, 'make')
+
+
+elif target_os == 'msys_nt':
+ if os.path.exists(gtest_dir):
+ gtest_lib_dir = gtest_dir + '/lib'
+ gtest_dotlib_dir = gtest_lib_dir + '/.libs'
+ if not os.path.exists(gtest_lib_dir):
+ # Create lib dir
+ os.mkdir(gtest_lib_dir)
+ os.mkdir(gtest_dotlib_dir)
+
+ # Run configure on gtest
+ print 'Configuring google unit test for compilation'
+ env.Configure(gtest_dir, 'cmake -G "Unix Makefiles" .')
# Run make on gtest
print 'Making google unit test'
env.Configure(gtest_dir, 'make')
+ print 'Moving libraries to lib folder'
+ env.Configure(gtest_dir, 'cp libgtest.a lib')
+ env.Configure(gtest_dir, 'mv libgtest.a lib/.libs')
+ env.Configure(gtest_dir, 'cp libgtest_main.a lib')
+ env.Configure(gtest_dir, 'mv libgtest_main.a lib/.libs')
+
+elif target_os == 'windows':
+ if os.path.exists(gtest_dir):
+ gtest_lib_dir = os.path.join(gtest_dir, 'lib')
+ gtest_dotlib_dir = os.path.join(gtest_lib_dir, '.libs')
+ if env.get('RELEASE'):
+ output_dir = os.path.join(gtest_dir, 'Release') + os.sep
+ else:
+ output_dir = os.path.join(gtest_dir, 'Debug') + os.sep
+
+ # Three parts to the gtest config string...
+ # 1. "Visual Studio" toolchain name.
+ # 2. VS Version + Year ("14 2015", "12 2013").
+ # 3. Target Architecture ("Win64", "Win32").
+ vs_version_year = ""
+ vs_target_arch = ""
+ vs_num = env['MSVC_VERSION']
+ if "12.0" in vs_num:
+ vs_version_year = "Visual Studio 12 2013"
+ elif "14.0" in vs_num:
+ vs_version_year = "Visual Studio 14 2015"
+ else:
+ print "Error: unknown Visual Studio version %s" % vs_num
+
+ vs_arch = env['TARGET_ARCH']
+ if "amd64" in vs_arch:
+ vs_target_arch = "Win64"
+ elif "x86" in vs_arch:
+ vs_target_arch = ""
+ else:
+ print "Error: unknown Visual Studio target arch %s" % vs_arch
+
+ vs_target_string = vs_version_year + " " + vs_target_arch
+
+ # Exit if we didn't get a match for one of the above.
+ if not vs_version_year or not vs_target_arch:
+ Exit(1)
+
+ if not env.WhereIs('cmake', env.get('PATH')):
+ print '''*********************** Error ************************
+* *
+* Please make sure that CMake is in your System PATH *
+* *
+* You can download CMake from: *
+* https://cmake.org/download/ *
+* *
+******************************************************
+'''
+ Exit(1)
+
+ if not os.path.exists(gtest_lib_dir):
+ # Create lib dir
+ os.mkdir(gtest_lib_dir)
+ os.mkdir(gtest_dotlib_dir)
+
+ # Run configure on gtest
+ print 'Configuring google unit test for compilation'
+ env.Configure(gtest_dir, 'cmake . -G"'+vs_target_string+'" -Dgtest_force_shared_crt=ON')
+
+ # Run make on gtest
+ print 'Making google unit test'
+ env.Configure(gtest_dir, 'msbuild gtest.vcxproj')
+ env.Configure(gtest_dir, 'msbuild gtest_main.vcxproj')
+
+ print 'Moving libraries to lib folder'
+ env.Configure(gtest_dir, 'copy '+output_dir+'gtest.lib %s' % gtest_lib_dir)
+ env.Configure(gtest_dir, 'move '+output_dir+'gtest.lib %s' % gtest_dotlib_dir )
+ env.Configure(gtest_dir, 'copy '+output_dir+'gtest_main.lib %s' % gtest_lib_dir)
+ env.Configure(gtest_dir, 'move '+output_dir+'gtest_main.lib %s' % gtest_dotlib_dir)
if target_os == 'linux':
print '*** Checking for installation of hippomocks ***'
- hippomocks_sha = '2f40aa11e31499432283b67f9d3449a3cd7b9c4d'
+ hippomocks_sha = '8e210c5808d490b26fff69151c801fa28d291fcb'
hippomocks_dir_src = src_dir + '/extlibs/hippomocks-' + hippomocks_sha
hippomocks_dir_dest = src_dir + '/extlibs/hippomocks-master'
hippomocks_zip_file = src_dir + '/extlibs/hippomocks-' + hippomocks_sha + '.zip'
target_os = sqlite_env.get('TARGET_OS')
src_dir = sqlite_env.get('SRC_DIR')
-targets_need_sqlite = ['linux', 'android', 'tizen']
+targets_need_sqlite = ['linux', 'android', 'tizen', 'msys_nt', 'windows']
sqlite_dir = src_dir + '/extlibs/sqlite3/'
sqlite_build_dir = src_dir + '/extlibs/sqlite3/sqlite-amalgamation-3081101/'
sqlite_zip_file = src_dir + '/extlibs/sqlite3/sqlite-amalgamation-3081101.zip'
-sqlite_url = 'http://www.sqlite.org/2015/sqlite-amalgamation-3081101.zip'
+sqlite_url = 'https://www.sqlite.org/2015/sqlite-amalgamation-3081101.zip'
# Download
if target_os in targets_need_sqlite:
os.remove(sqlite_zip_file)
shutil.rmtree(sqlite_build_dir)
-# Build will be done with provisioning manager module.
\ No newline at end of file
+# Build will be done with provisioning manager module.
# *****************************************************************/
Import('env')
-env.AppendUnique(TIMER_SRC = 'timer.c')
-
-libtimer = env.StaticLibrary('libtimer', env.get('TIMER_SRC'), OBJPREFIX='libtimer_')
-env.InstallTarget(libtimer, 'libtimer');
+timer_src = [ 'timer.c' ]
+libtimer = env.StaticLibrary('timer', timer_src, OBJPREFIX='libtimer_')
+env.InstallTarget(libtimer, 'timer');
#define _BSD_SOURCE
-#ifndef WITH_ARDUINO
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_MEMORY_H
#include <memory.h>
+#endif
+#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
-
+#ifdef HAVE_STRING_H
#include <string.h>
+#endif
+#include "platform_features.h"
+
#include <stdio.h>
#include "timer.h"
int initThread()
{
- int res;
- long t = 0;
-
- res = pthread_create(&thread_id, NULL, loop, (void *) t);
+ int res = pthread_create(&thread_id, NULL, loop, NULL);
if (res)
{
#ifndef TIMER_H_
#define TIMER_H_
-#ifndef WITH_ARDUINO
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
-#else
+#endif
+#ifdef HAVE_ARDUINO_TIME_H
#include <Time.h>
#endif
dtls_env.AppendUnique(CPPPATH = [root_dir+'ecc/'])
dtls_env.AppendUnique(CPPPATH = [root_dir+'sha2/'])
-if target_os not in ['arduino', 'windows', 'winrt']:
- dtls_env.AppendUnique(CPPDEFINES = ['HAVE_SYS_TIME_H'])
-
######################################################################
# Source files and Target(s)
######################################################################
if not env.get('RELEASE'):
samples_env = dtls_env.Clone()
- if target_os not in ['arduino', 'windows', 'winrt']:
+ if target_os not in ['arduino', 'windows']:
samples_env.AppendUnique(CPPDEFINES = ['_GNU_SOURCE'])
dtlsserver = samples_env.Program('dtls-server', ['tests/dtls-server.c'])
samples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
samples_env.PrependUnique(LIBS = ['tinydtls'])
+ if target_os in ['windows', 'msys_nt']:
+ samples_env.AppendUnique(LIBS = ['ws2_32', 'iphlpapi', 'advapi32'])
+
Alias("samples", [dtlsserver, dtlsclient])
samples_env.AppendTarget('samples')
* has finished */
#define DTLS_EVENT_RENEGOTIATE 0x01DF /**< re-negotiation has started */
-static inline int
+INLINE_API int
dtls_alert_create(dtls_alert_level_t level, dtls_alert_t desc)
{
return -((level << 8) | desc);
}
-static inline int
+INLINE_API int
dtls_alert_fatal_create(dtls_alert_t desc)
{
return dtls_alert_create(DTLS_ALERT_LEVEL_FATAL, desc);
(A)[i] |= (C) & 0xFF; \
}
-static inline void
+INLINE_API void
block0(size_t M, /* number of auth bytes */
size_t L, /* number of bytes to encode message length */
size_t la, /* l(a) octets additional authenticated data */
}
}
-static inline void
+INLINE_API void
encrypt(rijndael_ctx *ctx, size_t L, unsigned long counter,
unsigned char *msg, size_t len,
unsigned char A[DTLS_CCM_BLOCKSIZE],
memxor(msg, S, len);
}
-static inline void
+INLINE_API void
mac(rijndael_ctx *ctx,
unsigned char *msg, size_t len,
unsigned char B[DTLS_CCM_BLOCKSIZE],
#include "netq.h"
#include "hmac.h"
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
#include <pthread.h>
#endif
if (Seed) dtls_hmac_update(Context, (Seed), (Length))
static struct dtls_cipher_context_t cipher_context;
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
static pthread_mutex_t cipher_context_mutex = PTHREAD_MUTEX_INITIALIZER;
#endif
static struct dtls_cipher_context_t *dtls_cipher_context_get(void)
{
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
pthread_mutex_lock(&cipher_context_mutex);
#endif
return &cipher_context;
static void dtls_cipher_context_release(void)
{
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
pthread_mutex_unlock(&cipher_context_mutex);
#endif
}
/* The following macros provide access to the components of the
* key_block in the security parameters. */
-static inline int dtls_kb_mac_secret_size(dtls_cipher_t cipher)
+INLINE_API int dtls_kb_mac_secret_size(dtls_cipher_t cipher)
{
switch(cipher)
{
}
-static inline int dtls_kb_iv_size(dtls_cipher_t cipher)
+INLINE_API int dtls_kb_iv_size(dtls_cipher_t cipher)
{
switch(cipher)
{
#ifdef HAVE_TIME_H
-static inline size_t
+INLINE_API size_t
print_timestamp(char *s, size_t len, time_t t) {
struct tm *tmp;
tmp = localtime(&t);
#else /* alternative implementation: just print the timestamp */
-static inline size_t
+INLINE_API size_t
print_timestamp(char *s, size_t len, clock_time_t t) {
#ifdef HAVE_SNPRINTF
return snprintf(s, len, "%u.%03u",
*
* @return The length of @p s.
*/
-static inline size_t
+INLINE_API size_t
dtls_strnlen(const char *s, size_t maxlen) {
size_t n = 0;
while(*s++ && n < maxlen)
static size_t
dsrv_print_addr(const session_t *addr, char *buf, size_t len) {
-#ifdef HAVE_ARPA_INET_H
+#if defined(HAVE_ARPA_INET_H) || defined(_WIN32)
const void *addrptr = NULL;
-#ifdef __ANDROID__
+#if defined(__ANDROID__) || defined(_WIN32)
unsigned short int port;
#else
in_port_t port;
#ifdef CONTIKI_TARGET_MBXXX
extern char __Stack_Init, _estack;
-static inline void check_stack() {
+INLINE_API void check_stack() {
const char *p = &__Stack_Init;
while (p < &_estack && *p == 0x38) {
p++;
PRINTF("Stack: %d bytes used (%d free)\n", &_estack - p, p - &__Stack_Init);
}
#else /* CONTIKI_TARGET_MBXXX */
-static inline void check_stack() {
+INLINE_API void check_stack() {
}
#endif /* CONTIKI_TARGET_MBXXX */
#else /* WITH_CONTKI */
#define PRINTF(...)
-static inline void check_stack() {
+INLINE_API void check_stack() {
}
#endif
#else /* NDEBUG */
-static inline log_t dtls_get_log_level()
+INLINE_API log_t dtls_get_log_level()
{
return DTLS_LOG_EMERG;
}
-static inline void dtls_set_log_level(log_t level)
+INLINE_API void dtls_set_log_level(log_t level)
{}
-static inline void dsrv_log(log_t level, char *format, ...)
+INLINE_API void dsrv_log(log_t level, char *format, ...)
{}
-static inline void hexdump(const unsigned char *packet, int length)
+INLINE_API void hexdump(const unsigned char *packet, int length)
{}
-static inline void dump(unsigned char *buf, size_t len)
+INLINE_API void dump(unsigned char *buf, size_t len)
{}
-static inline void
+INLINE_API void
dtls_dsrv_hexdump_log(log_t level, const char *name, const unsigned char *buf, size_t length, int extend)
{}
-static inline void
+INLINE_API void
dtls_dsrv_log_addr(log_t level, const char *name, const struct __session_t *addr)
{}
static dtls_context_t the_dtls_context;
-static inline dtls_context_t *
+INLINE_API dtls_context_t *
malloc_context() {
return &the_dtls_context;
}
-static inline void
+INLINE_API void
free_context(dtls_context_t *context) {
}
#else /* WITH_CONTIKI */
-static inline dtls_context_t *
+INLINE_API dtls_context_t *
malloc_context() {
return (dtls_context_t *)malloc(sizeof(dtls_context_t));
}
-static inline void
+INLINE_API void
free_context(dtls_context_t *context) {
free(context);
}
*/
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;
* \return pointer to the next byte after the written header.
* The length will be set to 0 and has to be changed before sending.
*/
-static inline uint8 *
+INLINE_API uint8 *
dtls_set_record_header(uint8 type, dtls_security_parameters_t *security,
uint8 *buf) {
* bytes. Increments message sequence number counter of \p peer.
* \return pointer to the next byte after \p buf
*/
-static inline uint8 *
+INLINE_API uint8 *
dtls_set_handshake_header(uint8 type, dtls_peer_t *peer,
int length,
int frag_offset, int frag_length,
};
/** returns true if the cipher matches TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
-static inline int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
+INLINE_API int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
{
#if defined(DTLS_ECC) || defined(DTLS_X509)
return cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
}
/** returns true if the cipher matches TLS_PSK_WITH_AES_128_CCM_8 */
-static inline int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
+INLINE_API int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
{
#ifdef DTLS_PSK
return cipher == TLS_PSK_WITH_AES_128_CCM_8;
}
/** returns true if the cipher matches TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 */
-static inline int is_tls_ecdh_anon_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
+INLINE_API int is_tls_ecdh_anon_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
{
#ifdef DTLS_ECC
return cipher == TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256;
}
/** returns true if the cipher matches TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 */
-static inline int is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
+INLINE_API int is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
{
#if defined(DTLS_ECC) && defined(DTLS_PSK)
return cipher == TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256;
/** returns true if the application is configured for psk */
-static inline int is_psk_supported(dtls_context_t *ctx)
+INLINE_API int is_psk_supported(dtls_context_t *ctx)
{
#ifdef DTLS_PSK
return ctx && ctx->h && ctx->h->get_psk_info;
}
/** returns true if the application is configured for ecdhe_ecdsa */
-static inline int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
+INLINE_API int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
{
#ifdef DTLS_ECC
return ctx && ctx->h && ((!is_client && ctx->h->get_ecdsa_key) ||
}
/** returns true if the application is configured for x509 */
-static inline int is_x509_supported(dtls_context_t *ctx, int is_client)
+INLINE_API int is_x509_supported(dtls_context_t *ctx, int is_client)
{
#ifdef DTLS_X509
return ctx && ctx->h && ((!is_client && ctx->h->get_x509_cert) ||
/** Returns true if the application is configured for ecdhe_ecdsa with
* client authentication */
-static inline int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
+INLINE_API int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
{
#ifdef DTLS_ECC
return ctx && ctx->h && ctx->h->get_ecdsa_key && ctx->h->verify_ecdsa_key;
/** Returns true if the application is configured for x509 with
* client authentication */
-static inline int is_x509_client_auth_supported(dtls_context_t *ctx)
+INLINE_API int is_x509_client_auth_supported(dtls_context_t *ctx)
{
#ifdef DTLS_X509
return ctx && ctx->h && ctx->h->get_x509_cert && ctx->h->verify_x509_cert;
}
/** returns true if ecdh_anon_with_aes_128_cbc_sha is supported */
-static inline int is_ecdh_anon_supported(dtls_context_t *ctx)
+INLINE_API int is_ecdh_anon_supported(dtls_context_t *ctx)
{
#ifdef DTLS_ECC
return ctx && (ctx->is_anon_ecdh_eabled == DTLS_CIPHER_ENABLE);
}
/** returns true if ecdhe_psk_with_aes_128_cbc_sha_256 is supported */
-static inline int is_ecdhe_psk_supported(dtls_context_t *ctx)
+INLINE_API int is_ecdhe_psk_supported(dtls_context_t *ctx)
{
#if defined(DTLS_ECC) && defined(DTLS_PSK)
return is_psk_supported(ctx);
* Parse the ClientKeyExchange and update the internal handshake state with
* the new data.
*/
-static inline int
+INLINE_API int
check_client_keyexchange(dtls_context_t *ctx,
dtls_handshake_parameters_t *handshake,
uint8 *data, size_t length) {
return 0;
}
-static inline void
+INLINE_API void
update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length) {
dtls_debug_dump("add MAC data", data, length);
dtls_hash_update(&peer->handshake_params->hs_state.hs_hash, data, length);
sizeof(peer->handshake_params->hs_state.hs_hash));
}
-static inline size_t
+INLINE_API size_t
finalize_hs_hash(dtls_peer_t *peer, uint8 *buf) {
return dtls_hash_finalize(buf, &peer->handshake_params->hs_state.hs_hash);
}
-static inline void
+INLINE_API void
clear_hs_hash(dtls_peer_t *peer) {
assert(peer);
dtls_debug("clear MAC\n");
return res <= 0 ? res : overall_len - (len - res);
}
-static inline int
+INLINE_API int
dtls_send_alert(dtls_context_t *ctx, dtls_peer_t *peer, dtls_alert_level_t level,
dtls_alert_t description) {
uint8_t msg[] = { level, description };
return 0;
}
-static inline int
+INLINE_API int
dtls_send_ccs(dtls_context_t *ctx, dtls_peer_t *peer) {
uint8 buf[1] = {1};
* 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
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",
}
if (free_peer) {
- dtls_stop_retransmission(ctx, peer);
+ dtls_clear_retransmission(ctx, peer);
dtls_destroy_peer(ctx, peer, 0);
}
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 */
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");
DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
/* invalidate peer */
+ dtls_clear_retransmission(ctx, peer);
dtls_destroy_peer(ctx, peer, 1);
peer = NULL;
}
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) {
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);
// 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:
dtls_new_context(void *app_data) {
dtls_context_t *c;
dtls_tick_t now;
-#ifndef WITH_CONTIKI
+#if defined(_WIN32)
+ unsigned int randValue;
+ errno_t err;
+#endif
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
FILE *urandom = fopen("/dev/urandom", "r");
unsigned char buf[sizeof(unsigned long)];
#endif /* WITH_CONTIKI */
#ifdef WITH_CONTIKI
/* FIXME: need something better to init PRNG here */
dtls_prng_init(now);
+#elif defined(_WIN32)
+ err = rand_s(&randValue);
+ if (err != 0)
+ {
+ dtls_emerg("cannot initialize PRNG\n");
+ return NULL;
+ }
+ dtls_prng_init(randValue);
#else /* WITH_CONTIKI */
if (!urandom) {
dtls_emerg("cannot initialize PRNG\n");
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) {
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);
+ }
}
}
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
#define dtls_get_app_data(CTX) ((CTX)->app)
/** Sets the callback handler object for @p ctx to @p h. */
-static inline void dtls_set_handler(dtls_context_t *ctx, dtls_handler_t *h) {
+INLINE_API void dtls_set_handler(dtls_context_t *ctx, dtls_handler_t *h) {
ctx->h = h;
}
#define DTLS_CT_HANDSHAKE 22
#define DTLS_CT_APPLICATION_DATA 23
+#if defined(_MSC_VER)
+#define PACKED_STRUCT __pragma(pack(1)) typedef struct
+#else
+#define PACKED_STRUCT typedef struct __attribute__((__packed__))
+#endif
+
/** Generic header structure of the DTLS record layer. */
-typedef struct __attribute__((__packed__)) {
+PACKED_STRUCT {
uint8 content_type; /**< content type of the included message */
uint16 version; /**< Protocol version */
uint16 epoch; /**< counter for cipher state changes */
#define DTLS_HT_FINISHED 20
/** Header structure for the DTLS handshake protocol. */
-typedef struct __attribute__((__packed__)) {
+PACKED_STRUCT {
uint8 msg_type; /**< Type of handshake message (one of DTLS_HT_) */
uint24 length; /**< length of this message */
uint16 message_seq; /**< Message sequence number */
} dtls_handshake_header_t;
/** Structure of the Client Hello message. */
-typedef struct __attribute__((__packed__)) {
+PACKED_STRUCT {
uint16 version; /**< Client version */
uint32 gmt_random; /**< GMT time of the random byte creation */
unsigned char random[28]; /**< Client random bytes */
} dtls_client_hello_t;
/** Structure of the Hello Verify Request. */
-typedef struct __attribute__((__packed__)) {
+PACKED_STRUCT {
uint16 version; /**< Server version */
uint8 cookie_length; /**< Length of the included cookie */
uint8 cookie[]; /**< up to 32 bytes making up the cookie */
#define DTLS_X509 1
/* Define to 1 if you have the <arpa/inet.h> header file. */
+#ifndef _WIN32
#define HAVE_ARPA_INET_H 1
+#endif
/* Define to 1 if you have the <assert.h> header file. */
#define HAVE_ASSERT_H 1
#define HAVE_MEMSET 1
/* Define to 1 if you have the <netdb.h> header file. */
+#ifndef _WIN32
#define HAVE_NETDB_H 1
+#endif
/* Define to 1 if you have the <netinet/in.h> header file. */
+#ifndef _WIN32
#define HAVE_NETINET_IN_H 1
+#endif
/* Define to 1 if you have the `select' function. */
#define HAVE_SELECT 1
#define HAVE_SYS_PARAM_H 1
/* Define to 1 if you have the <sys/socket.h> header file. */
+#ifndef _WIN32
#define HAVE_SYS_SOCKET_H 1
+#endif
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/time.h> header file. */
+#ifndef _WIN32
#define HAVE_SYS_TIME_H 1
+#endif
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+#define ssize_t SSIZE_T
+#define snprintf vs12_snprintf
+#endif
+#if defined(_WIN32)
+#define MSG_DONTWAIT 0
+#define HAVE_WINSOCK2_H 1
+#define HAVE_WS2TCPIP_H 1
+#endif
/************************************************************************/
/* Specific Contiki platforms */
}
#else /* WITH_CONTIKI */
+#ifdef _WIN32
+#include <windows.h>
+#endif
time_t dtls_clock_offset;
void
dtls_clock_init(void) {
+#ifdef _WIN32
+ /* Use clock offset in milliseconds */
+ dtls_clock_offset = GetTickCount();
+#else
#ifdef HAVE_TIME_H
+ /* Use clock offset in seconds */
dtls_clock_offset = time(NULL);
#else
# ifdef __GNUC__
# endif
dtls_clock_offset = 0;
#endif
+#endif
}
void dtls_ticks(dtls_tick_t *t) {
+#ifdef _WIN32
+ *t = ((GetTickCount() - dtls_clock_offset) * DTLS_TICKS_PER_SECOND / 1000);
+#else
#ifdef HAVE_SYS_TIME_H
struct timeval tv;
gettimeofday(&tv, NULL);
#else
#error "clock not implemented"
#endif
+#endif
}
#endif /* WITH_CONTIKI */
#define _DTLS_DTLS_TIME_H_
#include <stdint.h>
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
#include "tinydtls.h"
/**
* XORs \p n bytes byte-by-byte starting at \p y to the memory area
* starting at \p x. */
-static inline void
+INLINE_API void
memxor(unsigned char *x, const unsigned char *y, size_t n) {
while(n--) {
*x ^= *y;
* \param len Number of bytes to compare.
* \return \c 1 if \p a and \p b are equal, \c 0 otherwise.
*/
-static inline int
+INLINE_API int
equals(unsigned char *a, unsigned char *b, size_t len) {
int result = 1;
while (len--) {
#ifdef HAVE_FLS
#define dtls_fls(i) fls(i)
#else
-static inline int
+INLINE_API int
dtls_fls(unsigned int i) {
int n;
for (n = 0; i; n++)
#ifndef WITH_CONTIKI
#include <stdlib.h>
-static inline dtls_hmac_context_t *
+INLINE_API dtls_hmac_context_t *
dtls_hmac_context_new() {
return (dtls_hmac_context_t *)malloc(sizeof(dtls_hmac_context_t));
}
-static inline void
+INLINE_API void
dtls_hmac_context_free(dtls_hmac_context_t *ctx) {
free(ctx);
}
#include "memb.h"
MEMB(hmac_context_storage, dtls_hmac_context_t, DTLS_HASH_MAX);
-static inline dtls_hmac_context_t *
+INLINE_API dtls_hmac_context_t *
dtls_hmac_context_new() {
return (dtls_hmac_context_t *)memb_alloc(&hmac_context_storage);
}
-static inline void
+INLINE_API void
dtls_hmac_context_free(dtls_hmac_context_t *ctx) {
memb_free(&hmac_context_storage, ctx);
}
* see http://www.aarongifford.com/ */
#include "sha2/sha2.h"
-typedef DTLS_SHA256_CTX dtls_hash_ctx;
+typedef dtls_sha256_ctx dtls_hash_ctx;
typedef dtls_hash_ctx *dtls_hash_t;
-#define DTLS_HASH_CTX_SIZE sizeof(DTLS_SHA256_CTX)
+#define DTLS_HASH_CTX_SIZE sizeof(dtls_sha256_ctx)
-static inline void
+INLINE_API void
dtls_hash_init(dtls_hash_t ctx) {
- DTLS_SHA256_Init((DTLS_SHA256_CTX *)ctx);
+ dtls_sha256_init((dtls_sha256_ctx *)ctx);
}
-static inline void
+INLINE_API void
dtls_hash_update(dtls_hash_t ctx, const unsigned char *input, size_t len) {
- DTLS_SHA256_Update((DTLS_SHA256_CTX *)ctx, input, len);
+ dtls_sha256_update((dtls_sha256_ctx *)ctx, input, len);
}
-static inline size_t
+INLINE_API size_t
dtls_hash_finalize(unsigned char *buf, dtls_hash_t ctx) {
- DTLS_SHA256_Final(buf, (DTLS_SHA256_CTX *)ctx);
+ dtls_sha256_final(buf, (dtls_sha256_ctx *)ctx);
return DTLS_SHA256_DIGEST_LENGTH;
}
#endif /* WITH_SHA256 */
#ifndef WITH_CONTIKI
-static inline void dtls_hmac_storage_init()
+INLINE_API void dtls_hmac_storage_init()
{ }
#else
void dtls_hmac_storage_init();
#ifndef WITH_CONTIKI
#include <stdlib.h>
-static inline netq_t *
+INLINE_API netq_t *
netq_malloc_node(size_t size) {
return (netq_t *)malloc(sizeof(netq_t) + size);
}
-static inline void
+INLINE_API void
netq_free_node(netq_t *node) {
free(node);
}
MEMB(netq_storage, netq_t, NETQ_MAXCNT);
-static inline netq_t *
+INLINE_API netq_t *
netq_malloc_node(size_t size) {
return (netq_t *)memb_alloc(&netq_storage);
}
-static inline void
+INLINE_API void
netq_free_node(netq_t *node) {
memb_free(&netq_storage, node);
}
} netq_t;
#ifndef WITH_CONTIKI
-static inline void netq_init()
+INLINE_API void netq_init()
{ }
#else
void netq_init();
#endif
/* this one is for consistency... */
-static inline int dtls_int_to_uint8(unsigned char *field, uint8_t value)
+INLINE_API int dtls_int_to_uint8(unsigned char *field, uint8_t value)
{
field[0] = value & 0xff;
return 1;
}
-static inline int dtls_int_to_uint16(unsigned char *field, uint16_t value)
+INLINE_API int dtls_int_to_uint16(unsigned char *field, uint16_t value)
{
field[0] = (value >> 8) & 0xff;
field[1] = value & 0xff;
return 2;
}
-static inline int dtls_int_to_uint24(unsigned char *field, uint32_t value)
+INLINE_API int dtls_int_to_uint24(unsigned char *field, uint32_t value)
{
field[0] = (value >> 16) & 0xff;
field[1] = (value >> 8) & 0xff;
return 3;
}
-static inline int dtls_int_to_uint32(unsigned char *field, uint32_t value)
+INLINE_API int dtls_int_to_uint32(unsigned char *field, uint32_t value)
{
field[0] = (value >> 24) & 0xff;
field[1] = (value >> 16) & 0xff;
return 4;
}
-static inline int dtls_int_to_uint48(unsigned char *field, uint64_t value)
+INLINE_API int dtls_int_to_uint48(unsigned char *field, uint64_t value)
{
field[0] = (value >> 40) & 0xff;
field[1] = (value >> 32) & 0xff;
return 6;
}
-static inline int dtls_int_to_uint64(unsigned char *field, uint64_t value)
+INLINE_API int dtls_int_to_uint64(unsigned char *field, uint64_t value)
{
field[0] = (value >> 56) & 0xff;
field[1] = (value >> 48) & 0xff;
return 8;
}
-static inline uint8_t dtls_uint8_to_int(const unsigned char *field)
+INLINE_API uint8_t dtls_uint8_to_int(const unsigned char *field)
{
return (uint8_t)field[0];
}
-static inline uint16_t dtls_uint16_to_int(const unsigned char *field)
+INLINE_API uint16_t dtls_uint16_to_int(const unsigned char *field)
{
return ((uint16_t)field[0] << 8)
| (uint16_t)field[1];
}
-static inline uint32_t dtls_uint24_to_int(const unsigned char *field)
+INLINE_API uint32_t dtls_uint24_to_int(const unsigned char *field)
{
return ((uint32_t)field[0] << 16)
| ((uint32_t)field[1] << 8)
| (uint32_t)field[2];
}
-static inline uint32_t dtls_uint32_to_int(const unsigned char *field)
+INLINE_API uint32_t dtls_uint32_to_int(const unsigned char *field)
{
return ((uint32_t)field[0] << 24)
| ((uint32_t)field[1] << 16)
| (uint32_t)field[3];
}
-static inline uint64_t dtls_uint48_to_int(const unsigned char *field)
+INLINE_API uint64_t dtls_uint48_to_int(const unsigned char *field)
{
return ((uint64_t)field[0] << 40)
| ((uint64_t)field[1] << 32)
| (uint64_t)field[5];
}
-static inline uint64_t dtls_uint64_to_int(const unsigned char *field)
+INLINE_API uint64_t dtls_uint64_to_int(const unsigned char *field)
{
return ((uint64_t)field[0] << 56)
| ((uint64_t)field[1] << 48)
{
}
-static inline dtls_peer_t *
+INLINE_API dtls_peer_t *
dtls_malloc_peer() {
return (dtls_peer_t *)malloc(sizeof(dtls_peer_t));
}
memb_init(&peer_storage);
}
-static inline dtls_peer_t *
+INLINE_API dtls_peer_t *
dtls_malloc_peer() {
return memb_alloc(&peer_storage);
}
dtls_handshake_parameters_t *handshake_params;
} dtls_peer_t;
-static inline dtls_security_parameters_t *dtls_security_params_epoch(dtls_peer_t *peer, uint16_t epoch)
+INLINE_API dtls_security_parameters_t *dtls_security_params_epoch(dtls_peer_t *peer, uint16_t epoch)
{
if (peer->security_params[0] && peer->security_params[0]->epoch == epoch) {
return peer->security_params[0];
}
}
-static inline dtls_security_parameters_t *dtls_security_params(dtls_peer_t *peer)
+INLINE_API dtls_security_parameters_t *dtls_security_params(dtls_peer_t *peer)
{
return peer->security_params[0];
}
-static inline dtls_security_parameters_t *dtls_security_params_next(dtls_peer_t *peer)
+INLINE_API dtls_security_parameters_t *dtls_security_params_next(dtls_peer_t *peer)
{
if (peer->security_params[1])
dtls_security_free(peer->security_params[1]);
return peer->security_params[1];
}
-static inline void dtls_security_params_free_other(dtls_peer_t *peer)
+INLINE_API void dtls_security_params_free_other(dtls_peer_t *peer)
{
dtls_security_parameters_t * security0 = peer->security_params[0];
dtls_security_parameters_t * security1 = peer->security_params[1];
peer->security_params[1] = NULL;
}
-static inline void dtls_security_params_switch(dtls_peer_t *peer)
+INLINE_API void dtls_security_params_switch(dtls_peer_t *peer)
{
dtls_security_parameters_t * security = peer->security_params[1];
void dtls_free_peer(dtls_peer_t *peer);
/** Returns the current state of @p peer. */
-static inline dtls_state_t dtls_peer_state(const dtls_peer_t *peer) {
+INLINE_API dtls_state_t dtls_peer_state(const dtls_peer_t *peer) {
return peer->state;
}
* Checks if given @p peer is connected. This function returns
* @c 1 if connected, or @c 0 otherwise.
*/
-static inline int dtls_peer_is_connected(const dtls_peer_t *peer) {
+INLINE_API int dtls_peer_is_connected(const dtls_peer_t *peer) {
return peer->state == DTLS_STATE_CONNECTED;
}
* implementation for prng(). You might want to change prng() to use
* a better PRNG on your specific platform.
*/
-static inline int
+INLINE_API int
dtls_prng(unsigned char *buf, size_t len) {
while (len--)
*buf++ = rand() & 0xFF;
return 1;
}
-static inline void
+INLINE_API void
dtls_prng_init(unsigned short seed) {
srand(seed);
}
#include "random.h"
#ifdef HAVE_PRNG
-static inline int
+INLINE_API int
dtls_prng(unsigned char *buf, size_t len)
{
return contiki_prng_impl(buf, len);
* implementation for prng(). You might want to change prng() to use
* a better PRNG on your specific platform.
*/
-static inline int
+INLINE_API int
dtls_prng(unsigned char *buf, size_t len) {
unsigned short v = random_rand();
while (len > sizeof(v)) {
}
#endif /* HAVE_PRNG */
-static inline void
+INLINE_API void
dtls_prng_init(unsigned short seed) {
random_init(seed);
}
#else /* WITH_CONTIKI */
-static inline int
+INLINE_API int
_dtls_address_equals_impl(const session_t *a,
const session_t *b) {
if (a->ifindex != b->ifindex ||
#include <string.h>
+#include "dtls_config.h"
#include "tinydtls.h"
#include "global.h"
#else /* WITH_CONTIKI */
+#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
+#endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+#include <stdint.h>
typedef struct {
socklen_t size; /**< size of addr */
* 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 ************************/
/*** 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);
(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;
#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;
#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) {
}
/* 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) {
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);
}
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;
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) {
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);
*(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
{
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];
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);
(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;
#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;
#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) {
}
/* 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) {
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);
}
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;
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;
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);
*(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
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];
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);
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
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];
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
*/
#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 ******************************/
#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 */
#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 */
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);
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);
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;
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;
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;
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;
(struct_ptr)->LIST_CONCAT(name,_list) = NULL; \
}
-static inline void *
+INLINE_API void *
list_head(list_t list) {
return *list;
}
-static inline void
+INLINE_API void
list_remove(list_t list, void *item) {
LL_DELETE(*(struct list **)list, (struct list *)item);
}
-static inline void
+INLINE_API void
list_add(list_t list, void *item) {
list_remove(list, item);
LL_APPEND(*(struct list **)list, (struct list *)item);
}
-static inline void
+INLINE_API void
list_push(list_t list, void *item) {
LL_PREPEND(*(struct list **)list, (struct list *)item);
}
-static inline void *
+INLINE_API void *
list_pop(list_t list) {
struct list *l;
l = *list;
return l;
}
-static inline void
+INLINE_API void
list_insert(list_t list, void *previtem, void *newitem) {
if(previtem == NULL) {
list_push(list, newitem);
}
}
-static inline void *
+INLINE_API void *
list_item_next(void *item)
{
return item == NULL? NULL: ((struct list *)item)->next;
#include <stdio.h>
#include <string.h>
#include <errno.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
#include <ctype.h>
+#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
+#endif
#include <sys/types.h>
+#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
+#endif
+#ifdef HAVE_NETDB_H
#include <netdb.h>
+#endif
#include <signal.h>
+#include <getopt.h>
+#include "platform_features.h"
#include "global.h"
#include "debug.h"
dtls_free_context(dtls_context);
dtls_free_context(orig_dtls_context);
signal(sig, SIG_DFL);
+#ifdef _WIN32
+ exit(sig);
+#else
kill(getpid(), sig);
+#endif
}
/* stolen from libcoap: */
return 0;
}
- if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) ) < 0) {
+ if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on) ) < 0) {
dtls_alert("setsockopt SO_REUSEADDR: %s\n", strerror(errno));
}
#if 0
#endif
on = 1;
#ifdef IPV6_RECVPKTINFO
- if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on) ) < 0) {
+ if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, OPTVAL_T(&on), sizeof(on) ) < 0) {
#else /* IPV6_RECVPKTINFO */
- if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, &on, sizeof(on) ) < 0) {
+ if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, OPTVAL_T(&on), sizeof(on) ) < 0) {
#endif /* IPV6_RECVPKTINFO */
dtls_alert("setsockopt IPV6_PKTINFO: %s\n", strerror(errno));
}
#include <stdio.h>
#include <string.h>
#include <errno.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
+#endif
#include <sys/types.h>
+#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
+#ifdef HAVE_NETDB_H
#include <netdb.h>
+#endif
#include <signal.h>
+#include <getopt.h>
+#include "platform_features.h"
#include "tinydtls.h"
#include "dtls.h"
return 0;
}
- if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) ) < 0) {
+ if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on) ) < 0) {
dtls_alert("setsockopt SO_REUSEADDR: %s\n", strerror(errno));
}
#if 0
#endif
on = 1;
#ifdef IPV6_RECVPKTINFO
- if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on) ) < 0) {
+ if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, OPTVAL_T(&on), sizeof(on) ) < 0) {
#else /* IPV6_RECVPKTINFO */
- if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, &on, sizeof(on) ) < 0) {
+ if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, OPTVAL_T(&on), sizeof(on) ) < 0) {
#endif /* IPV6_RECVPKTINFO */
dtls_alert("setsockopt IPV6_PKTINFO: %s\n", strerror(errno));
}
#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])
/** Define to 1 if building with Hardware Abstraction Layer */
#define DTLS_CRYPTO_HAL 0
+#ifndef INLINE_API
+# if defined(__cplusplus)
+# define INLINE_API inline
+# else
+# ifdef _WIN32
+# define INLINE_API static __inline
+# else
+# define INLINE_API static inline
+# endif
+# endif
+#endif
+
#endif /* _DTLS_TINYDTLS_H_ */
(head)=(head)->next; \
} else { \
char *_tmp = (char*)(head); \
- while (head->next && (head->next != (del))) { \
- head = head->next; \
+ while ((head)->next && ((head)->next != (del))) { \
+ (head) = (head)->next; \
} \
- if (head->next) { \
- head->next = ((del)->next); \
+ if ((head)->next) { \
+ (head)->next = ((del)->next); \
} \
{ \
char **_head_alias = (char**)&(head); \
rm -rf $sourcedir/tmp/extlibs/tinycbor/tinycbor/.git
cp -R ./extlibs/cjson $sourcedir/tmp/extlibs
+cp -R ./extlibs/gtest $sourcedir/tmp/extlibs
cp -R ./extlibs/tinydtls $sourcedir/tmp/extlibs
cp -R ./extlibs/sqlite3 $sourcedir/tmp/extlibs
cp -R ./extlibs/timer $sourcedir/tmp/extlibs
build_sample = env.get('BUILD_SAMPLE')
src_dir = env.get('SRC_DIR')
-if target_os not in ['android', 'arduino', 'darwin', 'ios', 'tizen']:
+if target_os not in ['android', 'arduino', 'darwin', 'ios', 'tizen', 'msys_nt', 'windows']:
SConscript(os.path.join('zigbee_wrapper', 'SConscript'))
static OCDeviceInfo deviceInfo =
{
.deviceName = "IoTivity/Zigbee Server Sample",
+ .specVersion = "IoTivity/Zigbee Device Spec Version",
};
+ char *dmv = OICStrdup("IoTivity/Zigbee Data Model Version");
+ deviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+ deviceInfo.dataModelVersions->value = dmv;
char *dup = OICStrdup("oic.wk.d");
deviceInfo.types = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
deviceInfo.types->value = dup;
- OICFree(dup);
return OCSetDeviceInfo(deviceInfo);
}
os.path.join(pi_path, 'include', 'internal')
])
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows']:
env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
if target_os in ['darwin','ios']:
calib = env.SharedLibrary('plugin_interface', env.get('PI_SRC'))
else:
calib = env.StaticLibrary('plugin_interface', env.get('PI_SRC'))
-env.InstallTarget(calib, 'libplugin_interface')
-env.UserInstallTargetLib(calib, 'libplugin_interface')
+env.InstallTarget(calib, 'plugin_interface')
+env.UserInstallTargetLib(calib, 'plugin_interface')
os.path.join(zw_path, 'zigbee_wrapper', 'include')
])
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows']:
env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
if target_os in ['darwin','ios']:
nodeId);
if(result != OC_STACK_OK)
{
- OIC_LOG_V(ERROR, TAG, "Failed to update Zigbee Resource NodeId due to result: %s", result);
+ OIC_LOG_V(ERROR, TAG, "Failed to update Zigbee Resource NodeId due to result: %u", result);
}
}
os.path.join(tw_path, 'zigbee_wrapper', 'telegesis_wrapper', 'include')
])
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows']:
env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
if target_os in ['darwin','ios']:
SEPARATOR_LENGTH + strlen(attributeType) +
SEPARATOR_LENGTH + strlen(newValue) + 1;
+ TWEntry* entry = NULL;
+
char* cmdString = (char*)OICMalloc(size * sizeof(char));
if (cmdString == NULL)
{
}
OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
- TWEntry* entry = NULL;
twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_WRITEATTR);
if (twRet != TW_RESULT_OK)
{
ret = OC_STACK_OK;
exit:
- TWDeleteEntry(ctx->g_plugin, entry);
+ if (entry != NULL)
+ {
+ TWDeleteEntry(ctx->g_plugin, entry);
+ }
OICFree(cmdString);
OIC_LOG_V(INFO, TAG, "Leave TWSetAttribute() with ret=%d", ret);
return ret;
SEPARATOR_LENGTH + strlen(clusterId) +
SEPARATOR_LENGTH + strlen(attributeId) + 1;
+ TWEntry* entry = NULL;
+
char* cmdString = (char*)OICMalloc(size * sizeof(char));
if (cmdString == NULL)
{
}
OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
- TWEntry* entry = NULL;
twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_RESPATTR);
if (twRet != TW_RESULT_OK)
{
ret = OC_STACK_OK;
exit:
- TWDeleteEntry(ctx->g_plugin, entry);
+ if (entry != NULL)
+ {
+ TWDeleteEntry(ctx->g_plugin, entry);
+ }
OICFree(cmdString);
OIC_LOG_V(INFO, TAG, "Leave TWGetAttribute() with ret=%d", ret);
return ret;
SEPARATOR_LENGTH + strlen(newState) + 1;
}
+ TWEntry* entry = NULL;
+
char* cmdString = (char*)OICMalloc(size * sizeof(char));
if (cmdString == NULL)
{
}
OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
- TWEntry* entry = NULL;
twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_DFTREP);
if (twRet != TW_RESULT_OK)
{
ret = OC_STACK_OK;
exit:
- TWDeleteEntry(ctx->g_plugin, entry);
+ if (entry != NULL)
+ {
+ TWDeleteEntry(ctx->g_plugin, entry);
+ }
OICFree(cmdString);
OIC_LOG_V(INFO, TAG, "Leave TWSwitchOnOff() with ret=%d", ret);
return ret;
SEPARATOR_LENGTH + strlen(level) +
SEPARATOR_LENGTH + strlen(transTime) + 1;
+ TWEntry* entry = NULL;
+
char* cmdString = (char*)OICMalloc(size * sizeof(char));
if (cmdString == NULL)
{
OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
- TWEntry* entry = NULL;
twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_DFTREP);
if (twRet != TW_RESULT_OK)
{
ret = OC_STACK_OK;
exit:
- TWDeleteEntry(ctx->g_plugin, entry);
+ if (entry != NULL)
+ {
+ TWDeleteEntry(ctx->g_plugin, entry);
+ }
OICFree(cmdString);
OIC_LOG_V(INFO, TAG, "Leave TWMoveToLevel() with ret=%d", ret);
return ret;
SEPARATOR_LENGTH + strlen(SENDMODE) +
SEPARATOR_LENGTH + strlen(newState) + 1;
+ TWEntry* entry = NULL;
+
char* cmdString = (char*)OICMalloc(size * sizeof(char));
if (cmdString == NULL)
{
OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
- TWEntry* entry = NULL;
twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_DFTREP);
if (twRet != TW_RESULT_OK)
{
ret = OC_STACK_OK;
exit:
- TWDeleteEntry(ctx->g_plugin, entry);
+ if (entry != NULL)
+ {
+ TWDeleteEntry(ctx->g_plugin, entry);
+ }
OICFree(cmdString);
OIC_LOG_V(INFO, TAG, "Leave TWSwitchDoorLockState() with ret=%d", ret);
return ret;
SEPARATOR_LENGTH + strlen(colorTemperature) +
SEPARATOR_LENGTH + strlen(transTime) + 1;
+ TWEntry* entry = NULL;
+
char* cmdString = (char*)OICMalloc(size * sizeof(char));
if (cmdString == NULL)
{
}
OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
- TWEntry* entry = NULL;
twRet = TWDequeueEntry(ctx->g_plugin, &entry, TW_DFTREP);
if (twRet != TW_RESULT_OK)
{
ret = OC_STACK_OK;
exit:
- TWDeleteEntry(ctx->g_plugin, entry);
+ if (entry != NULL)
+ {
+ TWDeleteEntry(ctx->g_plugin, entry);
+ }
OICFree(cmdString);
OIC_LOG_V(INFO, TAG, "Leave TWColorMoveToColorTemperature() with ret=%d", ret);
return ret;
OIC_LOG(INFO, TAG, "Enter CreatePAN()");
+ TWEntry* entry = NULL;
+ TWEntry* entry2 = NULL;
TWResultCode twRet1 = TW_RESULT_UNKNOWN;
TWResultCode twRet2 = TW_RESULT_UNKNOWN;
TWResultCode ret = TW_RESULT_UNKNOWN;
goto exit;
}
OIC_LOG_V(INFO, TAG, "Write %s", AT_CMD_GET_NETWORK_INFO);
- TWEntry* entry = NULL;
- TWEntry* entry2 = NULL;
ret = TWDequeueEntry(ctx->g_plugin, &entry, TW_NETWORK_INFO);
if (ret != TW_RESULT_OK)
{
}
exit:
- if (entry)
+ if (entry != NULL)
{
twRet1 = TWDeleteEntry(ctx->g_plugin, entry);
if(twRet1 != TW_RESULT_OK)
SEPARATOR_LENGTH + strlen(nodeId) +
SEPARATOR_LENGTH + strlen(endpoint) + 1;
+ TWEntry* entry = NULL;
+
char* cmdString = (char*)OICMalloc(size * sizeof(char));
if (cmdString == NULL)
{
}
OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
- TWEntry* entry = NULL;
ret = TWDequeueEntry(ctx->g_plugin, &entry, TW_SIMPLEDESC);
if (ret != TW_RESULT_OK)
{
}
exit:
- TWDeleteEntry(ctx->g_plugin, entry);
+ if (entry != NULL)
+ {
+ TWDeleteEntry(ctx->g_plugin, entry);
+ }
OICFree(cmdString);
OIC_LOG_V(INFO, TAG, "Leave FindClusters() with ret=%d", ret);
return ret;
int size = strlen(AT_CMD_REMOTE_EUI_REQUEST) + strlen(nodeId) +
SEPARATOR_LENGTH + strlen(nodeId) + 1;
+ TWEntry* entry = NULL;
+
char* cmdString = (char*)OICMalloc(size * sizeof(char));
if (cmdString == NULL)
{
}
OIC_LOG_V(INFO, TAG, "Write %s", cmdString);
- TWEntry* entry = NULL;
ret = TWDequeueEntry(ctx->g_plugin, &entry, TW_ADDRESS_RESPONSE);
if (ret != TW_RESULT_OK)
{
exit:
memset(ctx->g_WIPRemoteEUI, '\0', sizeof(ctx->g_WIPRemoteEUI));
memset(ctx->g_WIPRemoteNodeId, '\0', sizeof(ctx->g_WIPRemoteNodeId));
- TWDeleteEntry(ctx->g_plugin, entry);
+ if (entry != NULL)
+ {
+ TWDeleteEntry(ctx->g_plugin, entry);
+ }
OICFree(cmdString);
OIC_LOG_V(INFO, TAG, "Leave GetRemoteEUI() with ret=%d", ret);
return ret;
{
OIC_LOG(ERROR, TAG, "Invalid Params");
ret = TW_RESULT_ERROR_INVALID_PARAMS;
- goto exit;
+ goto exit;
}
if (ctx->g_WIPDevice == NULL)
#
##
-import os
-
Import('env')
target_os = env.get('TARGET_OS')
# Build liblogger
SConscript('csdk/logger/SConscript')
-if target_os not in ['arduino', 'darwin', 'ios', 'android']:
+if target_os not in ['arduino', 'darwin', 'ios', 'android', 'msys_nt', 'windows']:
env.AppendUnique(LIBS=['rt'])
# Build libcoap
# Build examples
SConscript('examples/SConscript')
-if target_os == 'linux':
+if target_os in ['linux', 'windows']:
# Build C Samples
SConscript('csdk/stack/samples/linux/SimpleClientServer/SConscript')
elif target_os == 'arduino':
SConscript('csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript')
+
+elif target_os == 'msys_nt':
+ # Build secure samples. Using linux samples for now.
+ SConscript('csdk/stack/samples/linux/secure/SConscript')
+
+ # Build C/C++ unit tests
+ SConscript('unit_tests.scons')
target_os = env.get('TARGET_OS')
+# Add platform-specific helper library
+if target_os in ['windows', 'msys_nt']:
+ SConscript('windows/SConscript')
+
env.AppendUnique(CPPPATH = [
os.path.join(Dir('.').abspath),
- os.path.join(Dir('.').abspath, 'oic_malloc/include'),
- os.path.join(Dir('.').abspath, 'oic_string/include'),
- os.path.join(Dir('.').abspath, 'oic_time/include'),
- os.path.join(Dir('.').abspath, 'ocrandom/include')
+ os.path.join(Dir('.').abspath, 'oic_malloc', 'include'),
+ os.path.join(Dir('.').abspath, 'oic_string', 'include'),
+ os.path.join(Dir('.').abspath, 'oic_time', 'include'),
+ os.path.join(Dir('.').abspath, 'ocrandom', 'include')
])
if target_os == 'tizen':
env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
else:
- env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/c_common')])
+ env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'c_common')])
if target_os in ['tizen', 'linux']:
env.ParseConfig("pkg-config --cflags --libs uuid")
env.PrependUnique(LIBS = ['c_common'])
common_env = env.Clone()
+common_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource')])
######################################################################
# Build flags
extern "C" {
#endif
-#if defined(__ANDROID__) || defined(__linux__)
+#ifndef ARDUINO
#include <time.h>
-#elif defined ARDUINO
+#else
// MEGA has 16 input pins whereas Due has only 12 input pins
#define ANALOG_IN (10)
#endif
#define _POSIX_C_SOURCE 200809L
#endif
-#if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__)
-#include "fcntl.h"
-#include "unistd.h"
+#include "platform_features.h"
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_STDLIB_H
#include <stdlib.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
+#ifdef HAVE_TIME_H
#include <time.h>
+#endif
#if defined(__ANDROID__)
#include <ctype.h>
#include <linux/time.h>
#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
#endif
#include "ocrandom.h"
#include <stdio.h>
-#if !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
+#ifdef HAVE_UUID_UUID_H
#include <uuid/uuid.h>
#endif
-#if !defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__) || defined(__TIZEN__)
#define NANO_SEC 1000000000
-#endif
#ifdef ARDUINO
#include "Arduino.h"
int8_t OCSeedRandom()
{
-#if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__) || defined(__TIZEN__)
+#ifndef ARDUINO
// Get current time to Seed.
uint64_t currentTime = 0;
#ifdef __ANDROID__
struct timespec getTs;
clock_gettime(CLOCK_MONOTONIC, &getTs);
currentTime = (getTs.tv_sec * (uint64_t)NANO_SEC + getTs.tv_nsec)/1000;
+#elif _WIN32
+ LARGE_INTEGER count;
+ if (QueryPerformanceCounter(&count)) {
+ currentTime = count.QuadPart;
+ }
#elif _POSIX_TIMERS > 0
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
gettimeofday(&tv, NULL);
currentTime = tv.tv_sec * (uint64_t)1000000 + tv.tv_usec;
#endif
-
+#if defined(__unix__) || defined(__APPLE__)
int32_t fd = open("/dev/urandom", O_RDONLY);
if (fd >= 0)
{
srand(randomSeed | currentTime);
}
else
+#endif
{
// Do time based seed when problem in accessing "/dev/urandom"
srand(currentTime);
uint8_t OCGetRandomByte(void)
{
-#if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__)
- return rand() & 0x00FF;
-#elif defined ARDUINO
#ifdef HAVE_SRANDOM
return random() & 0x00FF;
#else
return rand() & 0x00FF;
#endif
-#endif
}
uint32_t OCGetRandomRange(uint32_t firstBound, uint32_t secondBound)
uuid[15] = parseUuidPart(&uuidString[34]);
return RAND_UUID_OK;
-#elif !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
+#elif defined(HAVE_UUID_UUID_H)
// note: uuid_t is typedefed as unsigned char[16] on linux/apple
uuid_generate(uuid);
return RAND_UUID_OK;
close(fd);
return RAND_UUID_READ_ERROR;
}
-#elif !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
+#elif defined(HAVE_UUID_UUID_H)
uint8_t uuid[UUID_SIZE];
int8_t ret = OCGenerateUuid(uuid);
#define US_PER_MS (1000)
#define NS_PER_US (1000)
#define NS_PER_MS (1000000)
+#define HNS_PER_US (10)
#ifdef __cplusplus
#include <stddef.h> // For NULL
-#ifndef WITH_ARDUINO
+#if defined(_WIN32)
+# include <windows.h>
+#elif !defined(WITH_ARDUINO)
# if _POSIX_TIMERS > 0
# include <time.h> // For clock_gettime()
# else
#ifdef WITH_ARDUINO
currentTime = (TIME_IN_MS == precision) ? millis() : micros();
+#elif defined(_WIN32)
+ FILETIME fileTime;
+
+ GetSystemTimePreciseAsFileTime(&fileTime);
+
+ // fileTime should now be a QWORD hundred-nanoseconds time since 1601
+
+ // MSDN recommends using ULARGE_INTEGER as an intermediate representation for math.
+ ULARGE_INTEGER time = { .LowPart = fileTime.dwLowDateTime,
+ .HighPart = fileTime.dwHighDateTime };
+
+ currentTime =
+ (TIME_IN_MS == precision)
+ ? time.QuadPart / (HNS_PER_US * US_PER_MS)
+ : time.QuadPart / (HNS_PER_US);
#else
# if _POSIX_TIMERS > 0
# if defined(CLOCK_MONOTONIC_COARSE)
#if (__cplusplus >=201103L) || defined(__GXX_EXPERIMENTAL_CXX0X__)
- #define SUPPORTS_DEFAULT_CTOR
+# define SUPPORTS_DEFAULT_CTOR
#endif
#if (__STDC_VERSION__ >= 201112L)
- #include <assert.h>
- #define OC_STATIC_ASSERT(condition, msg) static_assert(condition, msg)
+# include <assert.h>
+# define OC_STATIC_ASSERT(condition, msg) static_assert(condition, msg)
+#elif defined(_WIN32)
+# if defined(__msys_nt__) && !defined(__cplusplus)
+# define static_assert _Static_assert
+# endif
+# define OC_STATIC_ASSERT(condition, msg) static_assert(condition, msg)
#else
- #define OC_STATIC_ASSERT(condition, msg) ((void)sizeof(char[2*!!(condition) - 1]))
+# define OC_STATIC_ASSERT(condition, msg) ((void)sizeof(char[2*!!(condition) - 1]))
+#endif
+
+#ifndef INLINE_API
+# if defined(__cplusplus)
+# define INLINE_API inline
+# else
+# ifdef _MSC_VER
+# define INLINE_API static __inline
+# else
+# define INLINE_API static inline
+# endif
+# endif
+#endif
+
+#ifdef _MSC_VER
+# ifdef OC_EXPORT_DLL
+# define OC_EXPORT __declspec(dllexport)
+# else
+# define OC_EXPORT __declspec(dllimport)
+# endif
+# ifdef ENABLE_TEST_EXPORTS
+# define OC_EXPORT_TEST OC_EXPORT
+# else
+# define OC_EXPORT_TEST
+# endif
+# define OC_ANNOTATE_UNUSED
+#else
+# define OC_ANNOTATE_UNUSED __attribute__((unused))
+# define OC_EXPORT
+# define OC_EXPORT_TEST
+#endif
+
+#ifdef _WIN32
+# define __func__ __FUNCTION__
+# define strncasecmp _strnicmp
+# define strtok_r strtok_s
+# if _MSC_VER && (_MSC_VER < 1900)
+# include "windows/include/vs12_snprintf.h"
+# endif
+# define ssize_t SSIZE_T
+# define F_OK 0
+# define sleep(SECS) Sleep(1000*(SECS))
+# ifdef __cplusplus
+# define SUPPORTS_DEFAULT_CTOR
+# endif
+# include "windows/include/win_sleep.h"
+# include "windows/include/pthread_create.h"
+#endif
+
+#ifdef HAVE_WINSOCK2_H
+# define OPTVAL_T(t) (const char*)(t)
+#else
+# define OPTVAL_T(t) (t)
#endif
#endif
--- /dev/null
+##
+# Builds Windows-specific helper library
+##
+Import('env')
+import os.path
+
+# Include any headers that might be missing on Windows
+env.AppendUnique(CPPPATH = [os.path.abspath('./include')])
+
+######################################################################
+# Source files and Targets
+######################################################################
+src_dir = os.path.abspath('./src')
+helper_src = [
+ os.path.join(src_dir, 'getopt.c'),
+ os.path.join(src_dir, 'win_sleep.c'),
+ os.path.join(src_dir, 'snprintf.c'),
+ os.path.join(src_dir, 'pthread_create.c')
+ ]
+
+static_libwinhelper = env.StaticLibrary('win_helper', helper_src)
+env.InstallTarget(static_libwinhelper, 'win_helper')
+env.UserInstallTargetLib(static_libwinhelper, 'win_helper')
+
+env.AppendUnique(LIBS = ['win_helper'])
+
--- /dev/null
+/** @todo: Add Microsoft license information */
+
+#ifndef GETOPT_H__
+#define GETOPT_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern char *optarg;
+extern int optind;
+
+int getopt(int argc, char *const argv[], const char *optstring);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
--- /dev/null
+/** @todo: Add Microsoft license information */
+
+#ifndef PTHREAD_CREATE_H__
+#define PTHREAD_CREATE_H__
+#ifndef WIN_PTHREADS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void* pthread_t;
+typedef void pthread_attr_t;
+
+int pthread_create(
+ pthread_t *thread,
+ const pthread_attr_t *attr,
+ void *(*start_routine)(void *),
+ void *arg);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //WIN_PTHREADS_H
+#endif //__PTHREAD_CREATE_H__
+
--- /dev/null
+/* *****************************************************************
+*
+* Copyright 2016 Intel Corporation
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#ifndef VS12_SNPRINTF_H__
+#define VS12_SNPRINTF_H__
+
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int vs12_snprintf(char *buffer, size_t count, const char *format, ...);
+
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+# define snprintf vs12_snprintf
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
--- /dev/null
+/* *****************************************************************
+*
+* Copyright 2016 Intel Corporation
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#ifndef WIN_SLEEP_H__
+#define WIN_SLEEP_H__
+
+#include <time.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+struct timespec
+{
+ time_t tv_sec; // Seconds - >= 0
+ long tv_nsec; // Nanoseconds - [0, 999999999]
+};
+#endif
+
+int nanosleep(const struct timespec *req, struct timespec *rem);
+int usleep(unsigned int usec);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
--- /dev/null
+/** @todo: Add Microsoft license information */
+
+#include "getopt.h"
+#include <windows.h>
+
+char* optarg = NULL;
+int optind = 1;
+
+int getopt(int argc, char *const argv[], const char *optstring)
+{
+ if ((optind >= argc) || (argv[optind][0] != '-') || (argv[optind][0] == 0))
+ {
+ return -1;
+ }
+
+ int opt = argv[optind][1];
+ const char *p = strchr(optstring, opt);
+
+ if (p == NULL)
+ {
+ return '?';
+ }
+ if (p[1] == ':')
+ {
+ optind++;
+ if (optind >= argc)
+ {
+ return '?';
+ }
+ optarg = argv[optind];
+ optind++;
+ }
+ return opt;
+}
+
--- /dev/null
+/** @todo: Add Microsoft license information */
+
+#include "pthread_create.h"
+#include <windows.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int pthread_create(
+ pthread_t *thread,
+ const pthread_attr_t *attr,
+ void *(*start_routine)(void *),
+ void *arg)
+{
+ *thread = CreateThread(NULL, 0, (PTHREAD_START_ROUTINE)start_routine, arg, 0, NULL);
+ return (*thread == NULL) ? GetLastError() : 0;
+}
+
+#ifdef __cplusplus
+}
+#endif
+
--- /dev/null
+/* *****************************************************************
+*
+* Copyright 2016 Intel Corporation
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include "vs12_snprintf.h"
+#include <stdio.h>
+#include <stdarg.h>
+
+int vs12_snprintf(char *buffer, size_t count, const char *format, ...)
+{
+ va_list args;
+
+ va_start(args, format);
+
+ int length = _vsnprintf(buffer, count, format, args);
+
+ va_end(args);
+
+ if (length > count)
+ {
+ buffer[count - 1] = '\0';
+ }
+
+ return length;
+}
+
--- /dev/null
+/* *****************************************************************
+*
+* Copyright 2016 Intel Corporation
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include <assert.h>
+#include <windows.h>
+#include <errno.h>
+#include "win_sleep.h"
+
+#include "logger.h"
+#define TAG "WIN_SLEEP"
+
+#define NS_PER_MS (1000000)
+#define US_PER_MS (1000)
+
+#define ASSERT_AND_FAIL(EXPRESSION) { \
+ assert((EXPRESSION)); \
+ if (!(EXPRESSION)) \
+ { \
+ errno = EINVAL; \
+ return -1; \
+ } \
+}
+
+int usleep(unsigned int usec)
+{
+ assert((usec % US_PER_MS) == 0); // granularity check
+ Sleep((usec + US_PER_MS - 1) / US_PER_MS);
+ return 0;
+}
+
+int nanosleep(const struct timespec *req, struct timespec *rem)
+{
+ if (req == NULL)
+ {
+ OIC_LOG(DEBUG, TAG, "nanosleep: req param should not be null");
+ }
+ ASSERT_AND_FAIL(req != NULL);
+ ASSERT_AND_FAIL(rem == NULL);
+ ASSERT_AND_FAIL(req->tv_sec == 0);
+ assert((req->tv_nsec % NS_PER_MS) == 0); // granularity check
+
+ Sleep((req->tv_nsec + NS_PER_MS - 1) / NS_PER_MS);
+
+ return 0;
+}
+
'security/provisioning/include',
])
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows']:
liboctbstack_env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
liboctbstack_env.AppendUnique(CFLAGS = ['-std=c99'])
elif liboctbstack_env.get('ROUTING') == 'EP':
liboctbstack_env.AppendUnique(CPPDEFINES = ['ROUTING_EP'])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
liboctbstack_env.AppendUnique(CFLAGS = ['-Wall'])
liboctbstack_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-if target_os in ['android', 'linux', 'tizen']:
+liboctbstack_env.PrependUnique(LIBS = ['ocsrm', 'coap'])
+if target_os in ['android', 'linux', 'tizen', 'msys_nt', 'windows']:
liboctbstack_env.PrependUnique(LIBS = ['connectivity_abstraction'])
if with_ra_ibb:
if with_ra:
liboctbstack_env.AppendUnique(LIBS = ['ra_xmpp'])
-liboctbstack_env.AppendUnique(LIBS = ['coap', 'm'])
-liboctbstack_env.PrependUnique(LIBS = ['ocsrm'])
+if target_os in ['windows', 'msys_nt']:
+ liboctbstack_env.AppendUnique(CPPDEFINES = ['OC_EXPORT_DLL'])
+ liboctbstack_env.AppendUnique(LIBS = ['ws2_32', 'advapi32', 'iphlpapi'])
+else:
+ liboctbstack_env.AppendUnique(LIBS = ['m'])
if target_os in ['tizen', 'linux']:
liboctbstack_env.ParseConfig("pkg-config --cflags --libs uuid")
-if target_os not in ['android', 'arduino', 'windows', 'winrt']:
+if target_os not in ['android', 'arduino', 'windows', 'msys_nt']:
liboctbstack_env.AppendUnique(LIBS = ['pthread'])
if target_os == 'arduino':
liboctbstack_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO'])
-elif target_os not in ['darwin','ios']:
+elif target_os not in ['darwin','ios', 'msys_nt', 'windows']:
liboctbstack_env.AppendUnique(CFLAGS = ['-fPIC'])
if target_os in ['darwin', 'ios']:
env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
liboctbstack_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
liboctbstack_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-if target_os not in ['arduino']:
+if target_os not in ['arduino', 'windows']:
liboctbstack_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
if target_os == 'android':
liboctbstack_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,liboctbstack.so'])
if env.get('WITH_RD') == '1':
liboctbstack_env.PrependUnique(CPPPATH = ['../../service/resource-directory/include'])
+ liboctbstack_env.PrependUnique(LIBPATH = [env.get('BUILD_DIR') + 'service/resource-directory/include'])
liboctbstack_env.AppendUnique(CPPDEFINES = ['-DWITH_RD'])
liboctbstack_env.AppendUnique(LIBS = ['resource_directory'])
liboctbstack_src.extend(env['cbor_files'])
-if target_os in ['arduino','darwin','ios'] :
- static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src)
- liboctbstack_env.InstallTarget(static_liboctbstack, 'liboctbstack')
- liboctbstack_env.UserInstallTargetLib(static_liboctbstack, 'liboctbstack')
- liboctbstack_env.UserInstallTargetHeader('stack/include/ocstackconfig.h', 'resource', 'ocstackconfig.h')
- liboctbstack_env.UserInstallTargetHeader('stack/include/octypes.h', 'resource', 'octypes.h')
-else:
- static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src)
+if target_os == 'windows':
+ liboctbstack_env.AppendUnique(CPPDEFINES = ['CBOR_API=__declspec(dllexport)',
+ 'CBOR_PRIVATE_API=__declspec(dllexport)'
+ ])
+
+static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src)
+octbstack_libs = Flatten(static_liboctbstack)
+
+if target_os not in ['arduino','darwin','ios'] :
shared_liboctbstack = liboctbstack_env.SharedLibrary('octbstack', liboctbstack_src)
- liboctbstack_env.InstallTarget([static_liboctbstack, shared_liboctbstack], 'liboctbstack')
- liboctbstack_env.UserInstallTargetLib([static_liboctbstack, shared_liboctbstack], 'liboctbstack')
- liboctbstack_env.UserInstallTargetHeader('stack/include/ocstackconfig.h', 'resource', 'ocstackconfig.h')
- liboctbstack_env.UserInstallTargetHeader('stack/include/octypes.h', 'resource', 'octypes.h')
+ octbstack_libs += Flatten(shared_liboctbstack)
liboctbstack_env.UserInstallTargetHeader('stack/include/ocstack.h', 'resource', 'ocstack.h')
liboctbstack_env.UserInstallTargetHeader('stack/include/ocpresence.h', 'resource', 'ocpresence.h')
+
+liboctbstack_env.InstallTarget(octbstack_libs, 'octbstack')
+liboctbstack_env.UserInstallTargetLib(octbstack_libs, 'octbstack')
+
+liboctbstack_env.UserInstallTargetHeader('stack/include/ocstackconfig.h', 'resource', 'ocstackconfig.h')
+liboctbstack_env.UserInstallTargetHeader('stack/include/octypes.h', 'resource', 'octypes.h')
env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER', 'NFC_ADAPTER'])
elif target_os in['darwin','ios']:
env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','NO_EDR_ADAPTER','NO_LE_ADAPTER'])
+ elif target_os in ['msys_nt', 'windows']:
+ env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','NO_EDR_ADAPTER','NO_LE_ADAPTER'])
else:
env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER'])
print "CA Transport is ALL"
#include <sys/poll.h>
#endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#include <mswsock.h>
+#endif
+
#ifdef __cplusplus
extern "C"
{
*/
typedef char *CAToken_t;
-// The following flags are the same as the equivalent OIC values in
-// octypes.h, allowing direct copying with slight fixup.
-// The CA layer should used the OC types when build allows that.
+/*
+ * Socket types and error definitions
+ */
+#ifdef HAVE_WINSOCK2_H
+# define OC_SOCKET_ERROR SOCKET_ERROR
+# define OC_INVALID_SOCKET INVALID_SOCKET
+typedef HANDLE CASocketFd_t;
+#else // HAVE_WINSOCK2_H
+# define OC_SOCKET_ERROR (-1)
+# define OC_INVALID_SOCKET (-1)
+typedef int CASocketFd_t;
+#endif
+
+/*
+ * The following flags are the same as the equivalent OIC values in
+ * octypes.h, allowing direct copying with slight fixup.
+ * The CA layer should used the OC types when build allows that.
+ */
#ifdef RA_ADAPTER
#define MAX_ADDR_STR_SIZE_CA (256)
#else
-#define MAX_ADDR_STR_SIZE_CA (40)
+/*
+ * Max Address could be "coap+tcp://[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:yyy.yyy.yyy.yyy]:xxxxx"
+ * Which is 64, +1 for null terminator => 65
+ * OCDevAddr (defined in OCTypes.h) must be the same
+ * as CAEndpoint_t (defined here)
+ */
+#define MAX_ADDR_STR_SIZE_CA (65)
#endif
typedef enum
CATransportFlags_t flags; // transport modifiers
uint16_t port; // for IP
char addr[MAX_ADDR_STR_SIZE_CA]; // address for all
- uint32_t interface; // usually zero for default interface
+ uint32_t ifindex; // usually zero for default interface
#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
char routeData[MAX_ADDR_STR_SIZE_CA]; /**< GatewayId:ClientId of
destination. **/
*/
typedef struct
{
- int fd; /**< socket fd */
- uint16_t port; /**< socket port */
+ CASocketFd_t fd; /**< socket fd */
+ uint16_t port; /**< socket port */
} CASocket_t;
#define HISTORYSIZE (4)
int32_t ifIndex; /**< network interface index */
} CAIfItem_t;
+/**
+ * Hold the port number assigned from application.
+ * It will be used when creating a socket.
+ */
+typedef struct
+{
+ struct udpports
+ {
+ uint16_t u6; /**< unicast IPv6 socket port */
+ uint16_t u6s; /**< unicast IPv6 socket secure port */
+ uint16_t u4; /**< unicast IPv4 socket port */
+ uint16_t u4s; /**< unicast IPv4 socket secure port */
+ } udp;
+#ifdef TCP_ADAPTER
+ struct tcpports
+ {
+ uint16_t u4; /**< unicast IPv4 socket port */
+ uint16_t u6; /**< unicast IPv6 socket port */
+ } tcp;
+#endif
+} CAPorts_t;
+
typedef struct
{
CATransportFlags_t clientFlags; /**< flag for client */
bool client; /**< client mode */
bool server; /**< server mode */
+ CAPorts_t ports;
+
struct sockets
{
- void *threadpool; /**< threadpool between Initialize and Start */
- CASocket_t u6; /**< unicast IPv6 */
- CASocket_t u6s; /**< unicast IPv6 secure */
- CASocket_t u4; /**< unicast IPv4 */
- CASocket_t u4s; /**< unicast IPv4 secure */
- CASocket_t m6; /**< multicast IPv6 */
- CASocket_t m6s; /**< multicast IPv6 secure */
- CASocket_t m4; /**< multicast IPv4 */
- CASocket_t m4s; /**< multicast IPv4 secure */
- int netlinkFd; /**< netlink */
- int shutdownFds[2]; /**< shutdown pipe */
- int selectTimeout; /**< in seconds */
- int maxfd; /**< highest fd (for select) */
- bool started; /**< the IP adapter has started */
- bool terminate; /**< the IP adapter needs to stop */
- bool ipv6enabled; /**< IPv6 enabled by OCInit flags */
- bool ipv4enabled; /**< IPv4 enabled by OCInit flags */
- bool dualstack; /**< IPv6 and IPv4 enabled */
+ void *threadpool; /**< threadpool between Initialize and Start */
+ CASocket_t u6; /**< unicast IPv6 */
+ CASocket_t u6s; /**< unicast IPv6 secure */
+ CASocket_t u4; /**< unicast IPv4 */
+ CASocket_t u4s; /**< unicast IPv4 secure */
+ CASocket_t m6; /**< multicast IPv6 */
+ CASocket_t m6s; /**< multicast IPv6 secure */
+ CASocket_t m4; /**< multicast IPv4 */
+ CASocket_t m4s; /**< multicast IPv4 secure */
+ CASocketFd_t netlinkFd; /**< netlink */
+#if defined(_WIN32)
+ WSAEVENT shutdownEvent; /**< Event used to signal threads to stop */
+#else
+ int shutdownFds[2]; /**< fds used to signal threads to stop */
+#endif
+ int selectTimeout; /**< in seconds */
+ int maxfd; /**< highest fd (for select) */
+ bool started; /**< the IP adapter has started */
+ bool terminate; /**< the IP adapter needs to stop */
+ bool ipv6enabled; /**< IPv6 enabled by OCInit flags */
+ bool ipv4enabled; /**< IPv4 enabled by OCInit flags */
+ bool dualstack; /**< IPv6 and IPv4 enabled */
+#if defined (_WIN32)
+ LPFN_WSARECVMSG wsaRecvMsg; /**< Win32 function pointer to WSARecvMsg() */
+#endif
struct networkmonitors
{
* 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.
*/
CAResult_t CAUnsetAutoConnectionDeviceInfo(const char* address);
+/**
+ * Set the port number to assign .
+ * @param[in] adapter Transport adapter information.
+ * @param[in] flag Transport flag information.
+ * @param[in] port The port number to use.
+ *
+ * @return ::CA_STATUS_OK or ::CA_STATUS_FAILED.
+ */
+CAResult_t CASetPortNumberToAssign(CATransportAdapter_t adapter,
+ CATransportFlags_t flag, uint16_t port);
+
+/**
+ * Get the assigned port number currently.
+ * @param[in] adapter Transport adapter information.
+ * @param[in] flag Transport flag information.
+ *
+ * @return assigned port number information.
+ */
+uint16_t CAGetAssignedPortNumber(CATransportAdapter_t adapter, CATransportFlags_t flag);
+
#ifdef __ANDROID__
/**
* initialize util client for android
* @param[in] listener callback listener
*/
void CAUtilSetFoundDeviceListener(jobject listener);
+
+/**
+ * set interval time and working count for LE scan.
+ * @param[in] intervalTime interval time(Seconds).
+ * @param[in] workingCount working cycle for selected interval time.
+ *
+ * @return ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
+ */
+CAResult_t CAUtilSetLEScanInterval(jint intervalTime, jint workingCount);
+
#endif
#ifdef __cplusplus
# Map of host os and allowed target os (host: allowed target os)
host_target_map = {
'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
- 'windows': ['windows', 'winrt', 'android', 'arduino'],
+ 'windows': ['windows', 'android', 'arduino'],
'darwin': ['darwin', 'ios', 'android', 'arduino'],
}
'tizen': ['x86', 'x86_64', 'arm', 'arm64'],
'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
'windows': ['x86', 'amd64', 'arm'],
- 'winrt': ['arm'],
'darwin': ['i386', 'x86_64'],
'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
'arduino': ['avr', 'arm'],
Exit(1)
if env.get('RELEASE'):
- build_dir = dir + '/out/' + target_os + '/' + target_arch + '/release/'
+ build_dir = os.path.join(dir, 'out', target_os, target_arch, 'release') + os.sep
else:
- build_dir = dir + '/out/' + target_os + '/' + target_arch + '/debug/'
+ build_dir = os.path.join(dir, 'out', target_os, target_arch, 'debug') + os.sep
env.VariantDir(build_dir, dir, duplicate=0)
env.Replace(BUILD_DIR = build_dir)
if user_prefix:
i_n = ienv.Install(user_prefix + '/lib', targets)
ienv.Alias("install", i_n)
+ else:
+ i_n = ienv.Install(env.get('BUILD_DIR') + '/lib', targets)
+ ienv.Alias("install", i_n)
def __installbin(ienv, targets, name):
user_prefix = env.get('PREFIX')
%define DEST_LIB_DIR %{buildroot}/%{_libdir}
Name: com-oic-ca
-Version: 0.1
-Release: 1
+Version: 1.1.1
+Release: 0
Summary: Tizen oicca application
URL: http://slp-source.sec.samsung.net
Source: %{name}-%{version}.tar.gz
ca_common_src_path + 'caremotehandler.c'
]
-if env['POSIX_SUPPORTED']:
+if env['POSIX_SUPPORTED'] or (ca_os in ['windows']):
platform_src = [
ca_common_src_path + 'cathreadpool_pthreads.c',
ca_common_src_path + 'camutex_pthreads.c'
typedef struct _tagMutexInfo_t
{
+#if defined(_MSC_VER)
+ uint8_t unused; //VS doesnt like empty structs
+#endif
} ca_mutex_internal;
typedef struct _tagEventInfo_t
{
+#if defined(_MSC_VER)
+ uint8_t unused; //VS doesnt like empty structs
+#endif
} ca_cond_internal;
/**
ca_mutex ca_mutex_new(void)
{
- return &g_mutexInfo;
+ return (ca_mutex)&g_mutexInfo;
}
bool ca_mutex_free(ca_mutex mutex)
ca_cond ca_cond_new(void)
{
- return &g_condInfo;
+ return (ca_cond)&g_condInfo;
}
void ca_cond_free(ca_cond cond)
#define _POSIX_C_SOURCE 200809L
#endif
+#ifdef HAVE_STRING_H
#include <string.h>
+#endif
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
-#include <errno.h>
+#endif
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_TIME_H
#include <time.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+#include <stdio.h>
+#include <errno.h>
#include <assert.h>
#include <oic_malloc.h>
-
+#include "platform_features.h"
#include "camutex.h"
#include "logger.h"
typedef struct _tagMutexInfo_t
{
+#if defined(_WIN32)
+ CRITICAL_SECTION mutex;
+#else
pthread_mutex_t mutex;
+#endif
} ca_mutex_internal;
typedef struct _tagEventInfo_t
{
+#if defined(_WIN32)
+ CONDITION_VARIABLE cond;
+#else
pthread_cond_t cond;
pthread_condattr_t condattr;
+#endif
} ca_cond_internal;
ca_mutex ca_mutex_new(void)
ca_mutex_internal *mutexInfo = (ca_mutex_internal*) OICMalloc(sizeof(ca_mutex_internal));
if (NULL != mutexInfo)
{
+#if defined(_WIN32)
+ InitializeCriticalSection(&mutexInfo->mutex);
+ retVal = (ca_mutex)mutexInfo;
+#else
// create the mutex with the attributes set
int ret=pthread_mutex_init(&(mutexInfo->mutex), PTHREAD_MUTEX_DEFAULT);
if (0 == ret)
OIC_LOG_V(ERROR, TAG, "%s Failed to initialize mutex !", __func__);
OICFree(mutexInfo);
}
+#endif
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "%s Failed to allocate mutex!", __func__);
}
return retVal;
ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
if (mutexInfo)
{
+#if defined(_WIN32)
+ DeleteCriticalSection(&mutexInfo->mutex);
+ OICFree(mutexInfo);
+ bRet=true;
+#else
int ret = pthread_mutex_destroy(&mutexInfo->mutex);
if (0 == ret)
{
{
OIC_LOG_V(ERROR, TAG, "%s Failed to free mutex !", __func__);
}
+#endif
}
else
{
ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
if (mutexInfo)
{
+#if defined(_WIN32)
+ EnterCriticalSection(&mutexInfo->mutex);
+#else
int ret = pthread_mutex_lock(&mutexInfo->mutex);
if(ret != 0)
{
OIC_LOG_V(ERROR, TAG, "Pthread Mutex lock failed: %d", ret);
exit(ret);
}
+#endif
}
else
{
ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
if (mutexInfo)
{
+#if defined(_WIN32)
+ LeaveCriticalSection(&mutexInfo->mutex);
+#else
int ret = pthread_mutex_unlock(&mutexInfo->mutex);
if(ret != 0)
{
exit(ret);
}
(void)ret;
+#endif
}
else
{
- OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex !", __func__);
- return;
+ OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex !", __func__);
+ return;
}
}
ca_cond_internal *eventInfo = (ca_cond_internal*) OICMalloc(sizeof(ca_cond_internal));
if (NULL != eventInfo)
{
+#if defined(_WIN32)
+ InitializeConditionVariable(&eventInfo->cond);
+ retVal = (ca_cond) eventInfo;
+#else
int ret = pthread_condattr_init(&(eventInfo->condattr));
if(0 != ret)
{
return retVal;
}
-#if defined(__ANDROID__) || _POSIX_TIMERS > 0
-#ifdef __ANDROID__
- if (camutex_condattr_setclock) {
+ #if defined(__ANDROID__) || _POSIX_TIMERS > 0
+ #ifdef __ANDROID__
+ if (camutex_condattr_setclock)
+ {
ret = camutex_condattr_setclock(&(eventInfo->condattr), CLOCK_MONOTONIC);
-#else
+ #else
{
ret = pthread_condattr_setclock(&(eventInfo->condattr), CLOCK_MONOTONIC);
-#endif /* __ANDROID__ */
+ #endif /* __ANDROID__ */
if(0 != ret)
{
OIC_LOG_V(ERROR, TAG, "%s: Failed to set condition variable clock %d!",
return retVal;
}
}
-#endif /* defined(__ANDROID__) || _POSIX_TIMERS > 0 */
+ #endif /* defined(__ANDROID__) || _POSIX_TIMERS > 0 */
ret = pthread_cond_init(&(eventInfo->cond), &(eventInfo->condattr));
if (0 == ret)
{
pthread_condattr_destroy(&(eventInfo->condattr));
OICFree(eventInfo);
}
+#endif
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "%s: Failed to allocate condition variable!", __func__);
}
return retVal;
ca_cond_internal *eventInfo = (ca_cond_internal*) cond;
if (eventInfo != NULL)
{
+#if defined(_WIN32)
+ OICFree(cond);
+#else
int ret = pthread_cond_destroy(&(eventInfo->cond));
int ret2 = pthread_condattr_destroy(&(eventInfo->condattr));
if (0 == ret && 0 == ret2)
OIC_LOG_V(ERROR, TAG, "%s: Failed to destroy condition variable %d, %d",
__func__, ret, ret2);
}
+#endif
}
else
{
ca_cond_internal *eventInfo = (ca_cond_internal*) cond;
if (eventInfo != NULL)
{
+#if defined(_WIN32)
+ WakeConditionVariable(&eventInfo->cond);
+#else
int ret = pthread_cond_signal(&(eventInfo->cond));
if (0 != ret)
{
OIC_LOG_V(ERROR, TAG, "%s: Failed to signal condition variable", __func__);
}
+#endif
}
else
{
ca_cond_internal* eventInfo = (ca_cond_internal*) cond;
if (eventInfo != NULL)
{
+#if defined(_WIN32)
+ WakeAllConditionVariable(&eventInfo->cond);
+#else
int ret = pthread_cond_broadcast(&(eventInfo->cond));
if (0 != ret)
{
OIC_LOG_V(ERROR, TAG, "%s: failed to signal condition variable", __func__);
}
+#endif
}
else
{
ca_cond_wait_for(cond, mutex, 0L);
}
+#ifndef TIMEVAL_TO_TIMESPEC
+#define TIMEVAL_TO_TIMESPEC(tv, ts) { \
+ (ts)->tv_sec = (tv)->tv_sec; \
+ (ts)->tv_nsec = (tv)->tv_usec * 1000; \
+}
+#endif
+
+#if !defined(_WIN32)
struct timespec ca_get_current_time()
{
#if defined(__ANDROID__) || _POSIX_TIMERS > 0
ts->tv_nsec = (totalNs)% NANOSECS_PER_SEC;
ts->tv_sec += secPart + secOfNs;
}
+#endif
CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseconds)
{
if (microseconds > 0)
{
+#if defined(_WIN32)
+ // Wait for the given time
+ DWORD milli = (DWORD)(microseconds / 1000);
+ if (!SleepConditionVariableCS(&eventInfo->cond, &mutexInfo->mutex, milli))
+ {
+ if (GetLastError() == ERROR_TIMEOUT)
+ {
+ retVal = CA_WAIT_TIMEDOUT;
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "SleepConditionVariableCS() with Timeout failed %i", GetLastError());
+ retVal = CA_WAIT_INVAL;
+ }
+ }else
+ {
+ retVal = CA_WAIT_SUCCESS;
+ }
+#else
int ret;
struct timespec abstime;
#ifdef __ANDROID__
- if (camutex_cond_timedwait_relative) {
+ if (camutex_cond_timedwait_relative)
+ {
abstime.tv_sec = microseconds / USECS_PER_SEC;
abstime.tv_nsec = (microseconds % USECS_PER_SEC) * NANOSECS_PER_USECS;
//Wait for the given time
retVal = CA_WAIT_INVAL;
break;
}
+#endif
}
else
{
+#if defined(_WIN32)
+ // Wait forever
+ if (!SleepConditionVariableCS(&eventInfo->cond, &mutexInfo->mutex, INFINITE))
+ {
+ OIC_LOG_V(ERROR, TAG, "SleepConditionVariableCS() w/o Timeout failed %i", GetLastError());
+ retVal = CA_WAIT_INVAL;
+ }else
+ {
+ retVal = CA_WAIT_SUCCESS;
+ }
+#else
// Wait forever
int ret = pthread_cond_wait(&eventInfo->cond, &mutexInfo->mutex);
retVal = ret == 0 ? CA_WAIT_SUCCESS : CA_WAIT_INVAL;
+#endif
}
-
return retVal;
}
#define _GNU_SOURCE
#endif
#include <errno.h>
+#if defined HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#if defined HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
#include "cathreadpool.h"
#include "logger.h"
#include "oic_malloc.h"
#include "uarraylist.h"
#include "camutex.h"
+#include "platform_features.h"
#define TAG PCF("UTHREADPOOL")
info->data = data;
pthread_t threadHandle;
-
int result = pthread_create(&threadHandle, NULL, ca_thread_pool_pthreads_delegate, info);
if(result != 0)
for(uint32_t i = 0; i<u_arraylist_length(thread_pool->details->threads_list); ++i)
{
pthread_t tid = (pthread_t)u_arraylist_get(thread_pool->details->threads_list, i);
+#if defined(_WIN32)
+ DWORD joinres = WaitForSingleObject(tid, INFINITE);
+ if (WAIT_OBJECT_0 != joinres)
+ {
+ OIC_LOG_V(ERROR, TAG, "Failed to join thread at index %u with error %d", i, joinres);
+ }
+ CloseHandle(tid);
+#else
int joinres = pthread_join(tid, NULL);
if(0 != joinres)
{
OIC_LOG_V(ERROR, TAG, "Failed to join thread at index %u with error %d", i, joinres);
}
+#endif
}
u_arraylist_free(&(thread_pool->details->threads_list));
#ifndef CA_ADAPTER_NET_DTLS_H_
#define CA_ADAPTER_NET_DTLS_H_
+#include "platform_features.h"
#include "dtls.h"
#include "uarraylist.h"
#include "camutex.h"
#include <jni.h>
#endif
-#ifndef WITH_ARDUINO
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+
+#if defined(HAVE_WINSOCK2_H) && defined(HAVE_WS2TCPIP_H)
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
/**
* Callback to notify connection information in the TCP adapter.
*
- * @param[in] addr connected device address.
- * @param[in] port connected port info.
- * @param[in] isConnected Whether keepalive message needs to be sent.
+ * @param[in] endpoint network endpoint description.
+ * @param[in] isConnected Whether keepalive message needs to be sent.
* @see Callback must be registered using CATCPSetKeepAliveCallback().
*/
-typedef void (*CATCPConnectionHandleCallback)(const char *addr, uint16_t port, bool isConnected);
+typedef void (*CATCPConnectionHandleCallback)(const CAEndpoint_t *endpoint, bool isConnected);
/**
* set error callback to notify error in TCP adapter.
void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback);
/**
+ * Set this callback for receiving the changed connection information from peer devices.
+ *
+ * @param[in] callback Callback to be notified when connection state changes.
+ */
+void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler);
+
+/**
* API to send unicast TCP data.
*
* @param[in] endpoint complete network address to send to.
*/
#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)
env.get('ARDUINO_HOME')+'/libraries/Ethernet/src/utility',
])
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows', 'msys_nt']:
libcoap_env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '_DEFAULT_SOURCE'])
libcoap_env.AppendUnique(CFLAGS = ['-std=gnu99','-fPIC'])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
libcoap_env.AppendUnique(CFLAGS = ['-Wall', '-ffunction-sections',
'-fdata-sections', '-fno-exceptions'])
+if target_os == 'msys_nt':
+ libcoap_env.AppendUnique(CPPDEFINES = ['_DEFAULT_SOURCE'])
+ libcoap_env.AppendUnique(CFLAGS = ['-std=c99'])
+
if target_os in ['linux', 'tizen', 'android', 'ios', 'arduino']:
if with_tcp == True:
libcoap_env.AppendUnique(CPPDEFINES = ['WITH_TCP'])
'block.c'
]
-libcoap = libcoap_env.StaticLibrary('libcoap', libcoap_src, OBJPREFIX='libcoap_')
+libcoap = libcoap_env.StaticLibrary('coap', libcoap_src, OBJPREFIX='libcoap_')
-libcoap_env.InstallTarget([libcoap], 'libcoap')
+libcoap_env.InstallTarget([libcoap], 'coap')
#include <sys/socket.h>
#endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+
#ifdef WITH_ARDUINO
#define DEV_ADDR_SIZE_MAX (16)
#endif
#define _coap_is_mcast_impl(Address) uip_is_addr_mcast(&((Address)->addr))
#endif /* WITH_CONTIKI */
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(_WIN32)
/** multi-purpose address abstraction */
typedef struct coap_address_t
}addr;
}coap_address_t;
-static inline int
+INLINE_API int
_coap_address_equals_impl(const coap_address_t *a,
const coap_address_t *b)
{
return 0;
}
-static inline int
+INLINE_API int
_coap_is_mcast_impl(const coap_address_t *a)
{
if (!a)
uint8_t addr[DEV_ADDR_SIZE_MAX]; /**< device address. */
} coap_address_t;
-static inline int
+INLINE_API int
_coap_address_equals_impl(const coap_address_t *a,
const coap_address_t *b)
{
return 1;
}
-static inline int
+INLINE_API int
_coap_is_mcast_impl(const coap_address_t *a)
{
if (!a)
*
* @param addr The coap_address_t object to initialize.
*/
-static inline void coap_address_init(coap_address_t *addr)
+INLINE_API void coap_address_init(coap_address_t *addr)
{
assert(addr);
memset(addr, 0, sizeof(coap_address_t));
* @c 1 if addresses are equal, @c 0 otherwise. The parameters @p a
* and @p b must not be @c NULL;
*/
-static inline int coap_address_equals(const coap_address_t *a, const coap_address_t *b)
+INLINE_API int coap_address_equals(const coap_address_t *a, const coap_address_t *b)
{
assert(a);
assert(b);
* Checks if given address @p a denotes a multicast address. This
* function returns @c 1 if @p a is multicast, @c 0 otherwise.
*/
-static inline int coap_is_mcast(const coap_address_t *a)
+INLINE_API int coap_is_mcast(const coap_address_t *a)
{
return a && _coap_is_mcast_impl(a);
}
*
* @param s The state object to update.
*/
-static inline void coap_touch_async(coap_async_state_t *s)
+INLINE_API void coap_touch_async(coap_async_state_t *s)
{
coap_ticks(&s->created);
}
*
* @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise.
*/
-inline static int bits_setb(uint8_t *vec, size_t size, uint8_t bit)
+INLINE_API int bits_setb(uint8_t *vec, size_t size, uint8_t bit)
{
if (size <= (size_t)(bit >> 3))
return -1;
*
* @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise.
*/
-inline static int bits_clrb(uint8_t *vec, size_t size, uint8_t bit)
+INLINE_API int bits_clrb(uint8_t *vec, size_t size, uint8_t bit)
{
if (size <= (size_t)(bit >> 3))
return -1;
*
* @return @c 1 if the bit is set, @c 0 otherwise.
*/
-inline static int bits_getb(const uint8_t *vec, size_t size, uint8_t bit)
+INLINE_API int bits_getb(const uint8_t *vec, size_t size, uint8_t bit)
{
if (size <= (size_t)(bit >> 3))
return -1;
* Checks if more than @p num blocks are required to deliver @p data_len
* bytes of data for a block size of 1 << (@p szx + 4).
*/
-static inline int coap_more_blocks(size_t data_len, unsigned int num, unsigned short szx)
+INLINE_API int coap_more_blocks(size_t data_len, unsigned int num, unsigned short szx)
{
return ((num + 1) << (szx + 4)) < data_len;
}
/** Sets the More-bit in @p block_opt */
-static inline void coap_opt_block_set_m(coap_opt_t *block_opt, int m)
+INLINE_API void coap_opt_block_set_m(coap_opt_t *block_opt, int m)
{
if (m)
*(COAP_OPT_VALUE(block_opt) + (COAP_OPT_LENGTH(block_opt) - 1)) |= 0x08;
#ifdef HAVE_TIME_H
#include <time.h>
#endif
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
#ifdef WITH_LWIP
#include <stdint.h>
typedef uint32_t coap_tick_t;
- static inline void coap_ticks_impl(coap_tick_t *t)
+ INLINE_API void coap_ticks_impl(coap_tick_t *t)
{
*t = sys_now();
}
- static inline void coap_clock_init_impl(void)
+ INLINE_API void coap_clock_init_impl(void)
{
}
/** Set at startup to initialize the internal clock (time in seconds). */
extern clock_time_t clock_offset;
- static inline void
+ INLINE_API void
contiki_clock_init_impl(void)
{
clock_init();
#define coap_clock_init contiki_clock_init_impl
- static inline void
+ INLINE_API void
contiki_ticks_impl(coap_tick_t *t)
{
*t = clock_time();
#define coap_ticks contiki_ticks_impl
#endif /* WITH_CONTIKI */
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(_WIN32)
typedef unsigned int coap_tick_t;
/**
/** Set at startup to initialize the internal clock (time in seconds). */
extern time_t clock_offset;
-#endif /* WITH_POSIX */
+#endif /* WITH_POSIX || _WIN32 */
#ifdef WITH_ARDUINO
#include "Time.h"
#endif /* WITH_ARDUINO */
#ifndef coap_clock_init
- static inline void coap_clock_init_impl(void)
+ INLINE_API void coap_clock_init_impl(void)
{
#ifdef HAVE_TIME_H
clock_offset = time(NULL);
#endif /* coap_clock_init */
#ifndef coap_ticks
- static inline void coap_ticks_impl(coap_tick_t *t)
+ INLINE_API void coap_ticks_impl(coap_tick_t *t)
{
#ifdef HAVE_SYS_TIME_H
struct timeval tv;
#endif
*t = (tv - clock_offset) * COAP_TICKS_PER_SECOND;
# else
+#ifdef HAVE_TIME_H
+ time_t tv = time(NULL);
+ *t = difftime(tv, clock_offset) * COAP_TICKS_PER_SECOND;
+#else
# error "clock not implemented"
+#endif /* HAVE_TIME_H */
# endif /* WITH_ARDUINO */
#endif /* HAVE_SYS_TIME_H */
}
* Returns @c 1 if and only if @p a is less than @p b where less is
* defined on a signed data type.
*/
- static inline
+ INLINE_API
int coap_time_lt(coap_tick_t a, coap_tick_t b)
{
return ((coap_tick_diff_t)(a - b)) < 0;
* Returns @c 1 if and only if @p a is less than or equal @p b where
* less is defined on a signed data type.
*/
- static inline
+ INLINE_API
int coap_time_le(coap_tick_t a, coap_tick_t b)
{
return a == b || coap_time_lt(a, b);
/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */
-/* Define to 1 if you have the <arpa/inet.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_ARPA_INET_H 1
-#endif
-
/* Define to 1 if you have the <assert.h> header file. */
#define HAVE_ASSERT_H 1
/* Define to 1 if you have the `memset' function. */
#define HAVE_MEMSET 1
-/* Define to 1 if you have the <netdb.h> header file. */
-#define HAVE_NETDB_H 1
-
/* Define to 1 if you have the <netinet/in.h> header file. */
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO) && !defined(_WIN32)
#define HAVE_NETINET_IN_H 1
#endif
#define HAVE_STRRCHR 1
/* Define to 1 if you have the <syslog.h> header file. */
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO) && !defined(_WIN32)
#define HAVE_SYSLOG_H 1
#endif
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_SOCKET_H 1
-#endif
-
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
-/* Define to 1 if you have the <sys/time.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_TIME_H 1
+/* Define to 1 if you have the <sys/unistd.h> header file. */
+#if !defined(WITH_ARDUINO) && !defined(_WIN32)
+#define HAVE_SYS_UNISTD_H 1
#endif
-/* Define to 1 if you have the <sys/types.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_TYPES_H 1
+/* Define to 1 if you have <Ws2tcpip.h> header file. */
+#if defined(_WIN32)
+#define HAVE_WS2TCPIP_H 1
#endif
-/* Define to 1 if you have the <sys/unistd.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_UNISTD_H 1
+/* Define to 1 if you have <Winsock2.h> header file. */
+#if defined(_WIN32)
+#define HAVE_WINSOCK2_H 1
+#endif
+
+/* Define to 1 if you have <Windows.h> header file. */
+#if defined(_WIN32)
+#define HAVE_WINDOWS_H 1
#endif
/* Define to 1 if you have the <time.h> header file. */
#endif
/* Define to 1 if you have the <unistd.h> header file. */
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO) && !defined(_WIN32)
#define HAVE_UNISTD_H 1
#endif
# endif
#endif
+#ifndef INLINE_API
+# if defined(__cplusplus)
+# define INLINE_API inline
+# else
+# ifdef _MSC_VER
+# define INLINE_API static __inline
+# else
+# define INLINE_API static inline
+# endif
+# endif
+#endif
+
/* Define to rpl_malloc if the replacement function should be used. */
/* #undef malloc */
#ifdef HAVE_TIME_H
-static inline size_t print_timestamp(char *s, size_t len, coap_tick_t t)
+INLINE_API size_t print_timestamp(char *s, size_t len, coap_tick_t t)
{
struct tm *tmp;
time_t now = clock_offset + (t / COAP_TICKS_PER_SECOND);
#else /* alternative implementation: just print the timestamp */
-static inline size_t
+INLINE_API size_t
print_timestamp(char *s, size_t len, coap_tick_t t)
{
#ifdef HAVE_SNPRINTF
*
* @return The length of @p s.
*/
-static inline size_t
+INLINE_API size_t
strnlen(const char *s, size_t maxlen)
{
size_t n = 0;
size_t coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, size_t len)
{
-#ifdef HAVE_ARPA_INET_H
+#if defined(HAVE_ARPA_INET_H) || defined(_WIN32)
const void *addrptr = NULL;
#if defined(__ANDROID__)
__uint16_t port;
+#elif defined(_WIN32)
+ uint16_t port;
#else
in_port_t port;
#endif
return 0;
}
+#ifdef HAVE_SNPRINTF
p += snprintf((char *) p, buf + len - p + 1, ":%d", port);
+#else /* HAVE_SNPRINTF */
+ /* @todo manual conversion of port number */
+#endif /* HAVE_SNPRINTF */
return buf + len - p;
#else /* HAVE_ARPA_INET_H */
#if (BSD >= 199103) || defined(WITH_CONTIKI)
# include <string.h>
#else
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO) && !defined(_MSC_VER)
# include <strings.h>
#endif
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
+#ifdef _WIN32
+#define ssize_t SSIZE_T
+#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
#ifdef WITH_LWIP
#include <lwip/pbuf.h>
#include "block.h"
#include "net.h"
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
time_t clock_offset=0;
-static inline coap_queue_t *
+INLINE_API coap_queue_t *
coap_malloc_node()
{
return (coap_queue_t *)coap_malloc(sizeof(coap_queue_t));
}
-static inline void
+INLINE_API void
coap_free_node(coap_queue_t *node)
{
coap_free(node);
static void coap_retransmittimer_execute(void *arg);
static void coap_retransmittimer_restart(coap_context_t *ctx);
-static inline coap_queue_t *
+INLINE_API coap_queue_t *
coap_malloc_node()
{
return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE);
}
-static inline void
+INLINE_API void
coap_free_node(coap_queue_t *node)
{
memp_free(MEMP_COAP_NODE, node);
PROCESS(coap_retransmit_process, "message retransmit process");
-static inline coap_queue_t *
+INLINE_API coap_queue_t *
coap_malloc_node()
{
return (coap_queue_t *)memb_alloc(&node_storage);
}
-static inline void
+INLINE_API void
coap_free_node(coap_queue_t *node)
{
memb_free(&node_storage, node);
coap_context_t *
coap_new_context(const coap_address_t *listen_addr)
{
-#if defined(WITH_POSIX)
+#if defined(WITH_POSIX) || defined(_WIN32)
coap_context_t *c = coap_malloc( sizeof( coap_context_t ) );
int reuse = 1;
#elif WITH_CONTIKI
coap_register_option(c, COAP_OPTION_BLOCK2);
coap_register_option(c, COAP_OPTION_BLOCK1);
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
c->sockfd = socket(listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0);
if ( c->sockfd < 0 )
{
goto onerror;
}
- if ( setsockopt( c->sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse) ) < 0 )
+ if ( setsockopt( c->sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse) ) < 0 )
{
#ifndef NDEBUG
coap_log(LOG_WARNING, "setsockopt SO_REUSEADDR\n");
void coap_free_context(coap_context_t *context)
{
-#if defined(WITH_POSIX) || defined(WITH_LWIP)
+#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(_WIN32)
coap_resource_t *res;
#ifndef COAP_RESOURCES_NOHASH
coap_resource_t *rtmp;
coap_retransmittimer_restart(context);
#endif
-#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO) || defined(_WIN32)
#ifdef COAP_RESOURCES_NOHASH
LL_FOREACH(context->resources, res)
{
}
#endif /* WITH_POSIX || WITH_LWIP */
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(_WIN32)
/* coap_delete_list(context->subscriptions); */
close( context->sockfd );
coap_free( context );
/* Compare the complete address structure in case of IPv4. For IPv6,
* we need to look at the transport address only. */
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(_WIN32)
switch (peer->addr.sa.sa_family)
{
case AF_INET:
}
#endif
-#if defined(WITH_POSIX)
+#if defined(WITH_POSIX) || defined(_WIN32)
/* releases space allocated by PDU if free_pdu is set */
coap_tid_t
coap_send_impl(coap_context_t *context,
if ( !context || !dst || !pdu )
return id;
- bytes_written = sendto( context->sockfd, pdu->hdr, pdu->length, 0,
+ bytes_written = sendto( context->sockfd, (char*)pdu->hdr, pdu->length, 0,
&dst->addr.sa, dst->size);
if (bytes_written >= 0)
* This function returns @c 1 on success, or @c 0 if the option @p opt
* would exceed @p maxpos.
*/
-static inline int check_opt_size(coap_opt_t *opt, unsigned char *maxpos)
+INLINE_API int check_opt_size(coap_opt_t *opt, unsigned char *maxpos)
{
if (opt && opt < maxpos)
{
#ifndef WITH_ARDUINO
int coap_read(coap_context_t *ctx)
{
-#if defined(WITH_POSIX)
+#if defined(WITH_POSIX) || defined(_WIN32)
static char buf[COAP_MAX_PDU_SIZE];
#endif
#if defined(WITH_LWIP) || defined(WITH_CONTIKI)
coap_address_init(&src);
-#if defined(WITH_POSIX)
+#if defined(WITH_POSIX) || defined(_WIN32)
bytes_read = recvfrom(ctx->sockfd, buf, sizeof(buf), 0, &src.addr.sa, &src.size);
#endif /* WITH_POSIX || WITH_ARDUINO */
}
-static inline int token_match(const unsigned char *a, size_t alen, const unsigned char *b,
+INLINE_API int token_match(const unsigned char *a, size_t alen, const unsigned char *b,
size_t blen)
{
return alen == blen && (alen == 0 || memcmp(a, b, alen) == 0);
* Quick hack to determine the size of the resource description for
* .well-known/core.
*/
-static inline size_t get_wkc_len(coap_context_t *context, coap_opt_t *query_filter)
+INLINE_API size_t get_wkc_len(coap_context_t *context, coap_opt_t *query_filter)
{
unsigned char buf[1];
size_t len = 0;
}
}
-static inline void handle_response(coap_context_t *context, coap_queue_t *sent, coap_queue_t *rcvd)
+INLINE_API void handle_response(coap_context_t *context, coap_queue_t *sent, coap_queue_t *rcvd)
{
/* Call application-specific reponse handler when available. If
}
}
-static inline int
+INLINE_API int
#ifdef __GNUC__
handle_locally(coap_context_t *context __attribute__ ((unused)),
coap_queue_t *node __attribute__ ((unused)))
* to sendqueue_basetime. */
coap_tick_t sendqueue_basetime;
coap_queue_t *sendqueue, *recvqueue;
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
int sockfd; /**< send/receive socket */
#endif /* WITH_POSIX || WITH_ARDUINO */
#ifdef WITH_CONTIKI
* @param context The context to register the handler for.
* @param handler The response handler to register.
*/
- static inline void coap_register_response_handler(coap_context_t *context,
+ INLINE_API void coap_register_response_handler(coap_context_t *context,
coap_response_handler_t handler)
{
context->response_handler = handler;
* @param ctx The context to use.
* @param type The option type to register.
*/
- inline static void coap_register_option(coap_context_t *ctx, unsigned char type)
+ INLINE_API void coap_register_option(coap_context_t *ctx, unsigned char type)
{
coap_option_setb(ctx->known_options, type);
}
* @param context the current coap_context_t object
* @return incremented message id in network byte order
*/
-static inline unsigned short coap_new_message_id(coap_context_t *context)
+INLINE_API unsigned short coap_new_message_id(coap_context_t *context)
{
++(context->message_id);
#if defined(WITH_ARDUINO)
* @return The transaction id if RST was sent or @c COAP_INVALID_TID
* on error.
*/
- static inline coap_tid_t coap_send_rst(coap_context_t *context, const coap_address_t *dst,
+ INLINE_API coap_tid_t coap_send_rst(coap_context_t *context, const coap_address_t *dst,
coap_pdu_t *request)
{
return coap_send_message_type(context, dst, request, COAP_MESSAGE_RST);
*
* @return @c 1 if node was found, removed and destroyed, @c 0 otherwise.
*/
- inline static int coap_remove_transaction(coap_queue_t **queue, coap_tid_t id)
+ INLINE_API int coap_remove_transaction(coap_queue_t **queue, coap_tid_t id)
{
coap_queue_t *node;
if (!coap_remove_from_queue(queue, id, &node))
return oi;
}
-static inline int opt_finished(coap_opt_iterator_t *oi)
+INLINE_API int opt_finished(coap_opt_iterator_t *oi)
{
assert(oi);
*
* @param f The filter to clear.
*/
-static inline void coap_option_filter_clear(coap_opt_filter_t f)
+INLINE_API void coap_option_filter_clear(coap_opt_filter_t f)
{
memset(f, 0, sizeof(coap_opt_filter_t));
}
*
* @return @c 1 if bit was set, @c -1 otherwise.
*/
-inline static int coap_option_setb(coap_opt_filter_t filter, unsigned short type)
+INLINE_API int coap_option_setb(coap_opt_filter_t filter, unsigned short type)
{
return bits_setb((uint8_t *) filter, sizeof(coap_opt_filter_t), type);
}
*
* @return @c 1 if bit was set, @c -1 otherwise.
*/
-inline static int coap_option_clrb(coap_opt_filter_t filter, unsigned short type)
+INLINE_API int coap_option_clrb(coap_opt_filter_t filter, unsigned short type)
{
return bits_clrb((uint8_t *) filter, sizeof(coap_opt_filter_t), type);
}
*
* @return @c 1 if bit was set, @c 0 if not, @c -1 on error.
*/
-inline static int coap_option_getb(const coap_opt_filter_t filter, unsigned short type)
+INLINE_API int coap_option_getb(const coap_opt_filter_t filter, unsigned short type)
{
return bits_getb((uint8_t *) filter, sizeof(coap_opt_filter_t), type);
}
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
#include "debug.h"
#include "pdu.h"
#endif
/* size must be large enough for hdr */
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
pdu = (coap_pdu_t *) coap_malloc(sizeof(coap_pdu_t) + size);
#endif
#ifdef WITH_CONTIKI
{
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;
}
{
struct
{
- unsigned int token_length :4; /* length of Token */
- unsigned int type :2; /* type flag */
- unsigned int version :2; /* protocol version */
- unsigned int code :8; /* request method (value 1--10) or response code (value 40-255) */
+ unsigned short token_length :4; /* length of Token */
+ unsigned short type :2; /* type flag */
+ unsigned short version :2; /* protocol version */
+ unsigned short code :8; /* request method (value 1--10) or response code (value 40-255) */
unsigned short id; /* transaction id (network byte order!) */
unsigned char token[]; /* the actual token, if any */
} coap_hdr_udp_t;
* implementation for prng(). You might want to change prng() to use
* a better PRNG on your specific platform.
*/
-static inline int coap_prng_impl(unsigned char *buf, size_t len)
+INLINE_API int coap_prng_impl(unsigned char *buf, size_t len)
{
while (len--)
*buf++ = rand() & 0xFF;
* implementation for prng(). You might want to change prng() to use
* a better PRNG on your specific platform.
*/
-static inline int
+INLINE_API int
contiki_prng_impl(unsigned char *buf, size_t len)
{
unsigned short v = random_rand();
#define COAP_FREE_TYPE(Type, Object) memp_free(MEMP_COAP_##Type, Object)
#endif
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
#include "utlist.h"
#include "mem.h"
}
#endif /* WITH_CONTIKI */
+#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
+#endif
/* Helper functions for conditional output of character sequences into
* a given buffer. The first Offset characters are skipped.
{
coap_resource_t *r;
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
r = (coap_resource_t *)coap_malloc(sizeof(coap_resource_t));
#endif
#ifdef WITH_LWIP
if (!resource || !name)
return NULL;
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
attr = (coap_attr_t *)coap_malloc(sizeof(coap_attr_t));
#endif
#ifdef WITH_LWIP
if (!resource)
return 0;
-#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO) || defined(_WIN32)
#ifdef COAP_RESOURCES_NOHASH
LL_DELETE(context->resources, resource);
#else
if (resource->flags & COAP_RESOURCE_FLAGS_RELEASE_URI)
coap_free(resource->uri.s);
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
coap_free(resource);
#endif
#ifdef WITH_LWIP
* @param method The CoAP request method to handle.
* @param handler The handler to register with @p resource.
*/
-static inline void coap_register_handler(coap_resource_t *resource, unsigned char method,
+INLINE_API void coap_register_handler(coap_resource_t *resource, unsigned char method,
coap_method_handler_t handler)
{
assert(resource);
(struct_ptr)->LIST_CONCAT(name,_list) = NULL; \
}
-static inline void *
+INLINE_API void *
list_head(list_t the_list)
{
return *the_list;
}
-static inline void list_remove(list_t the_list, void *item)
+INLINE_API void list_remove(list_t the_list, void *item)
{
if (list_head(the_list))
LL_DELETE(*(struct list **)the_list, (struct list *)item);
}
-static inline void list_add(list_t the_list, void *item)
+INLINE_API void list_add(list_t the_list, void *item)
{
list_remove(the_list, item);
LL_APPEND(*(struct list **)the_list, (struct list *)item);
}
-static inline void list_push(list_t the_list, void *item)
+INLINE_API void list_push(list_t the_list, void *item)
{
LL_PREPEND(*(struct list **)the_list, (struct list *)item);
}
-static inline void *
+INLINE_API void *
list_pop(list_t the_list)
{
struct list *l;
return l;
}
-static inline void list_insert(list_t the_list, void *previtem, void *newitem)
+INLINE_API void list_insert(list_t the_list, void *previtem, void *newitem)
{
if (previtem == NULL)
{
}
}
-static inline void *
+INLINE_API void *
list_item_next(void *item)
{
return item == NULL ? NULL : ((struct list *) item)->next;
* @return A pointer to the first occurence of @p c, or @c NULL
* if not found.
*/
-static inline unsigned char *
+INLINE_API unsigned char *
strnchr(unsigned char *s, size_t len, unsigned char c)
{
while (len && *s++ != c)
/* The function signature of coap_hash() is different from
* segment_handler_t hence we use this wrapper as safe typecast. */
-static inline void hash_segment(unsigned char *s, size_t len, void *data)
+INLINE_API void hash_segment(unsigned char *s, size_t len, void *data)
{
coap_hash(s, len, (unsigned char *) data);
}
when compiling c++ code), this code uses whatever method is needed
or, for VS2008 where neither is available, uses casting workarounds. */
#ifdef _MSC_VER /* MS compiler */
-#if _MSC_VER >= 1600 && __cplusplus /* VS2010 and newer in C++ mode */
+#if (_MSC_VER >= 1600) && (defined(__cplusplus) && (__cplusplus >= 201103L)) /* VS2010 and newer in C++ mode */
#define LDECLTYPE(x) decltype(x)
#else /* VS2008 or older (or VS2010 in C mode) */
#define NO_DECLTYPE
(head)=(head)->next; \
} else { \
char *_tmp = (char*)(head); \
- while (head->next && (head->next != (del))) { \
- head = head->next; \
+ while ((head)->next && ((head)->next != (del))) { \
+ (head) = (head)->next; \
} \
- if (head->next) { \
- head->next = ((del)->next); \
+ if ((head)->next) { \
+ (head)->next = ((del)->next); \
} \
{ \
char **_head_alias = (char**)&(head); \
env.PrependUnique(CPPPATH = [ os.path.join(root_dir, 'api') ])
env.AppendUnique(CPPPATH = [ os.path.join(root_dir, 'inc'),
- os.path.join(root_dir, 'lib/libcoap-4.1.1'),
- os.path.join(src_dir, '/resource/csdk/logger/include/'),
- os.path.join(root_dir, 'common/inc'),
- os.path.join(root_dir, 'util/inc') ])
+ os.path.join(root_dir, 'lib', 'libcoap-4.1.1'),
+ os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),
+ os.path.join(root_dir, 'common', 'inc'),
+ os.path.join(root_dir, 'util', 'inc') ])
-if ca_os not in ['arduino', 'windows', 'winrt']:
+if ca_os not in ['arduino', 'windows']:
env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
-if ca_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if ca_os not in ['darwin', 'ios', 'windows']:
env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
if ca_os in ['darwin','ios']:
env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
# Getting common source files
-env.SConscript('./../common/SConscript')
+env.SConscript(os.path.join(root_dir, 'common', 'SConscript'))
# Getting util source files
-env.SConscript(root_dir + '/util/SConscript')
+env.SConscript(os.path.join(root_dir, 'util', 'SConscript'))
# The tinydtls library is found in '#extlibs/tinydtls', where the '#'
# is interpreted by SCons as the top-level iotivity directory where
# the SConscruct file is found.
+build_dir = env.get('BUILD_DIR')
if env.get('SECURED') == '1':
- if ca_os == 'tizen' and os.path.exists(root_dir + '/extlibs/tinydtls'):
- env.SConscript(os.path.join(root_dir, 'extlibs/tinydtls/SConscript'))
- else:
- env.SConscript('#extlibs/tinydtls/SConscript')
- if ca_os == 'tizen' and os.path.exists(root_dir + '/extlibs/timer'):
- env.SConscript(os.path.join(root_dir, 'extlibs/timer/SConscript'))
- env.AppendUnique(CPPPATH = [os.path.join(root_dir, 'extlibs/timer')])
- else:
- env.SConscript('#extlibs/timer/SConscript')
- env.AppendUnique(CPPPATH = ['#extlibs/timer'])
+ env.SConscript(build_dir + 'extlibs/tinydtls/SConscript')
+ env.SConscript(build_dir + 'extlibs/timer/SConscript')
+ env.AppendUnique(CPPPATH = ['#extlibs/timer'])
env.AppendUnique(CA_SRC = [os.path.join(ca_path,
'adapter_util/caadapterutils.c')])
print "Include path is %s" % env.get('CPPPATH')
print "Files path is %s" % env.get('CA_SRC')
-
+
lib_env = env.Clone()
+if env.get('LOGGING'):
+ lib_env.AppendUnique(CPPDEFINES=['TB_LOG'])
+
if ca_os == 'android':
- lib_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,libconnectivity_abstraction.so'])
+ lib_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,libconnectivity_abstraction.so'])
if ca_os in ['android', 'tizen']:
lib_env.AppendUnique(LIBS = ['coap'])
lib_env.AppendUnique(LIBS = ['timer'])
if ca_os != 'android':
lib_env.AppendUnique(LIBS = ['rt'])
- calib = lib_env.SharedLibrary('connectivity_abstraction', lib_env.get('CA_SRC'))
+ calib = lib_env.SharedLibrary('connectivity_abstraction', env.get('CA_SRC'))
+elif ca_os in ['msys_nt', 'windows']:
+ lib_env.AppendUnique(LIBS = ['coap', 'mswsock', 'ws2_32', 'iphlpapi', 'logger'])
+ if lib_env.get('SECURED') == '1':
+ lib_env.AppendUnique(LIBS = ['tinydtls'])
+ lib_env.AppendUnique(LIBS = ['timer'])
+ calib = lib_env.StaticLibrary('connectivity_abstraction', env.get('CA_SRC'))
else:
calib = lib_env.StaticLibrary('connectivity_abstraction', lib_env.get('CA_SRC'))
-lib_env.InstallTarget(calib, 'libconnectivity_abstraction')
-lib_env.UserInstallTargetLib(calib, 'libconnectivity_abstraction')
+lib_env.InstallTarget(calib, 'connectivity_abstraction')
+lib_env.UserInstallTargetLib(calib, 'connectivity_abstraction')
#include "oic_string.h"
#include "global.h"
#include "timer.h"
+#if defined(HAVE_WINSOCK2_H) && defined(HAVE_WS2TCPIP_H)
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_NETDB_H
#include <netdb.h>
+#endif
/* tinyDTLS library error code */
#define TINY_DTLS_ERROR (-1)
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
endpoint.flags = addrInfo->addr.st.ss_family == AF_INET ? CA_IPV4 : CA_IPV6;
endpoint.flags |= CA_SECURE;
endpoint.adapter = CA_ADAPTER_IP;
- endpoint.interface = session->ifindex;
+ endpoint.ifindex = session->ifindex;
int type = 0;
//Mutex is not required for g_caDtlsContext. It will be called in same thread.
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);
}
{
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};
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
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()
#include "oic_malloc.h"
#include <errno.h>
-#ifndef WITH_ARDUINO
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
+#endif
+#if defined(HAVE_WINSOCK2_H) && defined(HAVE_WS2TCPIP_H)
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
NI_NUMERICHOST|NI_NUMERICSERV);
if (r)
{
+#if defined(EAI_SYSTEM)
if (EAI_SYSTEM == r)
{
OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
"getnameinfo failed: %s", gai_strerror(r));
}
+#elif defined(_WIN32)
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+ "getnameinfo failed: errno %i", WSAGetLastError());
+#else
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+ "getnameinfo failed: %s", gai_strerror(r));
+#endif
return;
}
*port = ntohs(((struct sockaddr_in *)sockAddr)->sin_port); // IPv4 and IPv6
int r = getaddrinfo(host, NULL, &hints, &addrs);
if (r)
{
+#if defined(EAI_SYSTEM)
if (EAI_SYSTEM == r)
{
OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
"getaddrinfo failed: %s", gai_strerror(r));
}
+#elif defined(_WIN32)
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+ "getaddrinfo failed: errno %i", WSAGetLastError());
+#else
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+ "getaddrinfo failed: %s", gai_strerror(r));
+#endif
return;
}
// assumption: in this case, getaddrinfo will only return one addrinfo
return CA_STATUS_INVALID_PARAM;
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
CAResult_t CAEDRCreateJNIInterfaceObject(jobject context)
{
- JNIEnv* env;
+ JNIEnv* env = NULL;
OIC_LOG(DEBUG, TAG, "CAEDRCreateJNIInterfaceObject");
if ((*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
OIC_LOG(DEBUG, TAG, "CAEDRTerminate");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
VERIFY_NON_NULL(data, TAG, "data is null");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
void CAEDRGetLocalAddress(char **address)
{
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
VERIFY_NON_NULL(data, TAG, "data is null");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
VERIFY_NON_NULL_VOID(data, TAG, "Invalid thread context");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
VERIFY_NON_NULL_VOID(data, TAG, "data is null");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
CAResult_t CAEDRServerStartAcceptThread()
{
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
return;
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth initialization failed!, error num [%x]",
ret);
- return;
+ return CA_STATUS_FAILED;
}
ret = bt_adapter_set_state_changed_cb(CAEDRAdapterStateChangeCallback, NULL);
if(BT_ERROR_NONE != ret)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "bt_adapter_set_state_changed_cb failed");
- return;
+ return CA_STATUS_FAILED;
}
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
#define MICROSECS_PER_SEC 1000000
#define WAIT_TIME_WRITE_CHARACTERISTIC 10 * MICROSECS_PER_SEC
+#define WAIT_TIME_SCAN_INTERVAL_DEFAULT 10
+#define WAIT_TIME_SCANNED_CHECKING 30
#define GATT_CONNECTION_PRIORITY_BALANCED 0
#define GATT_FAILURE 257
// it will be prevent to start send logic when adapter has stopped.
static bool g_isStartedLEClient = false;
-static bool g_isStartedScan = false;
static jbyteArray g_sendBuffer = NULL;
static uint32_t g_targetCnt = 0;
static ca_mutex g_deviceScanRetryDelayMutex = NULL;
static ca_cond g_deviceScanRetryDelayCond = NULL;
-static ca_mutex g_scanMutex = NULL;
+static ca_mutex g_threadScanIntervalMutex = NULL;
+static ca_cond g_threadScanIntervalCond = NULL;
+
static ca_mutex g_threadSendStateMutex = NULL;
+static int32_t g_scanIntervalTime = WAIT_TIME_SCAN_INTERVAL_DEFAULT;
+static int32_t g_scanIntervalTimePrev = WAIT_TIME_SCAN_INTERVAL_DEFAULT;
+static int32_t g_intervalCount = 0;
+static bool g_isWorkingScanThread = false;
+static CALEScanState_t g_scanningStep = BLE_SCAN_DISABLE;
+
static CABLEDataReceivedCallback g_CABLEClientDataReceivedCallback = NULL;
/**
return false;
}
+void CALEClientSetScanInterval(int32_t intervalTime, int32_t workingCount)
+{
+ OIC_LOG_V(DEBUG, TAG, "CALEClientSetScanInterval : %d -> %d",
+ g_scanIntervalTime, intervalTime);
+
+ // previous time should be stored.
+ if (0 < workingCount)
+ {
+ g_scanIntervalTimePrev = g_scanIntervalTime;
+ }
+ g_scanIntervalTime = intervalTime;
+ g_intervalCount = workingCount;
+}
+
+void CALERestartScanWithInterval(int32_t intervalTime, int32_t workingCount)
+{
+ // restart scan with interval
+ CALEClientSetScanInterval(intervalTime, workingCount);
+ ca_cond_signal(g_threadScanIntervalCond);
+}
+
+static void CALEScanThread(void* object)
+{
+ (void)object;
+
+ bool isAttached = false;
+ JNIEnv* env = NULL;
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (JNI_OK != res)
+ {
+ OIC_LOG(INFO, TAG, "Could not get JNIEnv pointer");
+ res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+
+ if (JNI_OK != res)
+ {
+ OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
+ return;
+ }
+ isAttached = true;
+ }
+
+ ca_mutex_lock(g_threadScanIntervalMutex);
+ while(g_isWorkingScanThread)
+ {
+ OIC_LOG(DEBUG, TAG, "scan waiting time out");
+ if (BLE_SCAN_ENABLE == g_scanningStep)
+ {
+ //stop scan
+ CAResult_t ret = CALEClientStopScan();
+ if (CA_STATUS_OK != ret)
+ {
+ OIC_LOG(INFO, TAG, "CALEClientStopScan has failed");
+ }
+ }
+ else
+ {
+ //start scan
+ CAResult_t ret = CALEClientStartScan();
+ if (CA_STATUS_OK != ret)
+ {
+ OIC_LOG(INFO, TAG, "CALEClientStartScan has failed");
+ }
+ }
+
+ OIC_LOG_V(DEBUG, TAG, "wait for Scan Interval Time during %d sec", g_scanIntervalTime);
+ if (CA_WAIT_SUCCESS == ca_cond_wait_for(g_threadScanIntervalCond,
+ g_threadScanIntervalMutex,
+ g_scanIntervalTime * MICROSECS_PER_SEC))
+ {
+ // called signal scan thread will be terminated
+ OIC_LOG(DEBUG, TAG, "signal scanInterval waiting");
+ g_scanningStep = BLE_SCAN_DISABLE;
+ }
+ else
+ {
+ if (BLE_SCAN_ENABLE == g_scanningStep)
+ {
+ if (g_intervalCount > 0)
+ {
+ if (g_intervalCount == 1)
+ {
+ OIC_LOG(DEBUG, TAG, "reset default time");
+ CALEClientSetScanInterval(g_scanIntervalTimePrev, 0);
+ }
+ g_intervalCount--;
+ OIC_LOG_V(DEBUG, TAG, "interval count : %d", g_intervalCount);
+ }
+ g_scanningStep = BLE_SCAN_DISABLE;
+ }
+ else
+ {
+ g_scanningStep = BLE_SCAN_ENABLE;
+ }
+ }
+ }
+ ca_mutex_unlock(g_threadScanIntervalMutex);
+
+ if (isAttached)
+ {
+ (*g_jvm)->DetachCurrentThread(g_jvm);
+ }
+}
+
+CAResult_t CALEClientStartScanWithInterval()
+{
+ OIC_LOG(DEBUG, TAG, "IN - CALEClientStartScanWithInterval");
+
+ if (g_isWorkingScanThread)
+ {
+ OIC_LOG(DEBUG, TAG, "scan interval logic already running");
+ return CA_STATUS_OK;
+ }
+
+ // initialize scan flags
+ g_scanningStep = BLE_SCAN_DISABLE;
+ g_isWorkingScanThread = true;
+ g_intervalCount = 0;
+ g_scanIntervalTime = g_scanIntervalTimePrev;
+
+ if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle,
+ CALEScanThread, NULL))
+ {
+ OIC_LOG(ERROR, TAG, "Failed to create read thread!");
+ g_isWorkingScanThread = false;
+ return CA_STATUS_FAILED;
+ }
+
+ OIC_LOG(DEBUG, TAG, "OUT - CALEClientStartScanWithInterval");
+ return CA_STATUS_OK;
+}
+
+void CALEClientStopScanWithInterval()
+{
+ g_isWorkingScanThread = false;
+ ca_cond_signal(g_threadScanIntervalCond);
+}
+
//getting jvm
void CALEClientJniInit()
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
g_threadCond = ca_cond_new();
g_threadWriteCharacteristicCond = ca_cond_new();
g_deviceScanRetryDelayCond = ca_cond_new();
+ g_threadScanIntervalCond = ca_cond_new();
CALEClientCreateDeviceList();
CALEClientJNISetContext();
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
OIC_LOG(ERROR, TAG, "CALEClientRemoveAllGattObjs has failed");
}
- CALEClientSetScanFlag(false);
CALEClientSetSendFinishFlag(true);
CALEClientTerminateGattMutexVariables();
ca_cond_free(g_threadCond);
ca_cond_free(g_threadWriteCharacteristicCond);
ca_cond_free(g_deviceScanRetryDelayCond);
+ ca_cond_free(g_threadScanIntervalCond);
g_deviceDescCond = NULL;
g_threadCond = NULL;
g_threadWriteCharacteristicCond = NULL;
g_deviceScanRetryDelayCond = NULL;
+ g_threadScanIntervalCond = NULL;
g_isSignalSetFlag = false;
+ // stop scanning
+ CALEClientStopScanWithInterval();
+
if (isAttached)
{
(*g_jvm)->DetachCurrentThread(g_jvm);
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
static uint64_t const TIMEOUT =
2 * MICROSECS_PER_SEC; // Microseconds
+ // set scan interval and start scan
+ CALERestartScanWithInterval(WAIT_TIME_SCANNED_CHECKING, 1);
+
bool devicesDiscovered = false;
for (size_t i = 0; i < RETRIES; ++i)
{
}
}
+ // reset scan interval time after checking scanned devices
+ CALERestartScanWithInterval(g_scanIntervalTimePrev, 0);
+
// time out for scanning devices
if (!devicesDiscovered)
{
CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t* data,
- const uint32_t dataLen)
+ const uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CALEClientSendUnicastMessageImpl, address: %s, data: %p", address,
data);
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
(*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
(*env)->DeleteLocalRef(env, jni_setAddress);
- // connect to gatt server
- ret = CALEClientStopScan();
- if (CA_STATUS_OK != ret)
- {
- OIC_LOG(ERROR, TAG, "CALEClientStopScan has failed");
- goto error_exit;
- }
+ // stop scan while sending
+ CALEClientStopScanWithInterval();
if (g_sendBuffer)
{
}
// start LE Scan again
- ret = CALEClientStartScan();
+ ret = CALEClientStartScanWithInterval();
if (CA_STATUS_OK != ret)
{
- OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+ OIC_LOG(ERROR, TAG, "CALEClientStartScanWithInterval has failed");
ca_mutex_unlock(g_threadSendMutex);
return ret;
}
}
// reset send state
- ret = CALEClientUpdateDeviceState(address, CA_LE_SEND_STATE,
- STATE_SEND_NONE);
- if (CA_STATUS_OK != ret)
+ CAResult_t resetRet = CALEClientUpdateDeviceState(address, CA_LE_SEND_STATE,
+ STATE_SEND_NONE);
+ if (CA_STATUS_OK != resetRet)
{
- OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
+ OIC_LOG_V(ERROR, TAG, "CALEClientUpdateDeviceState has failed (%d)", resetRet);
+ ret = CA_SEND_FAILED;
}
return ret;
error_exit:
// start LE Scan again
- ret = CALEClientStartScan();
+ ret = CALEClientStartScanWithInterval();
if (CA_STATUS_OK != ret)
{
- OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+ OIC_LOG(ERROR, TAG, "CALEClientStartScanWithInterval has failed");
ca_mutex_unlock(g_threadSendMutex);
if (isAttached)
{
goto error_exit;
}
- // connect to gatt server
- res = CALEClientStopScan();
- if (CA_STATUS_OK != res)
- {
- OIC_LOG(ERROR, TAG, "CALEClientStopScan has failed");
- ca_mutex_unlock(g_threadSendMutex);
- return res;
- }
+ // stop scan while sending
+ CALEClientStopScanWithInterval();
+
uint32_t length = u_arraylist_length(g_deviceList);
g_targetCnt = length;
ca_mutex_unlock(g_threadMutex);
// start LE Scan again
- res = CALEClientStartScan();
+ res = CALEClientStartScanWithInterval();
if (CA_STATUS_OK != res)
{
- OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+ OIC_LOG(ERROR, TAG, "CALEClientStartScanWithInterval has failed");
ca_mutex_unlock(g_threadSendMutex);
return res;
}
return CA_STATUS_OK;
error_exit:
- res = CALEClientStartScan();
+ res = CALEClientStartScanWithInterval();
if (CA_STATUS_OK != res)
{
- OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+ OIC_LOG(ERROR, TAG, "CALEClientStartScanWithInterval has failed");
ca_mutex_unlock(g_threadSendMutex);
return res;
}
return CA_STATUS_FAILED;
}
- if (g_isStartedScan)
- {
- OIC_LOG(INFO, TAG, "scanning is already started");
- return CA_STATUS_OK;
- }
-
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
if (!jni_mid_getDefaultAdapter)
{
OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
return CA_STATUS_FAILED;
}
if (!jni_mid_startLeScan)
{
OIC_LOG(ERROR, TAG, "startLeScan: jni_mid_startLeScan is null");
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
return CA_STATUS_FAILED;
}
if (!jni_obj_BTAdapter)
{
OIC_LOG(ERROR, TAG, "getState From BTAdapter: jni_obj_BTAdapter is null");
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
return CA_STATUS_FAILED;
}
else
{
OIC_LOG(DEBUG, TAG, "LeScan has started");
- CALEClientSetScanFlag(true);
}
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
+ (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
return CA_STATUS_OK;
}
if (!jni_mid_getDefaultAdapter)
{
OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
return CA_STATUS_FAILED;
}
if (!jni_mid_startLeScan)
{
OIC_LOG(ERROR, TAG, "startLeScan: jni_mid_startLeScan is null");
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
return CA_STATUS_FAILED;
}
if (!jni_obj_BTAdapter)
{
OIC_LOG(ERROR, TAG, "getState From BTAdapter: jni_obj_BTAdapter is null");
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
return CA_STATUS_FAILED;
}
else
{
OIC_LOG(DEBUG, TAG, "LeScan has started");
- CALEClientSetScanFlag(true);
}
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
+ (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
return CA_STATUS_OK;
}
return CA_STATUS_FAILED;
}
- if (!g_isStartedScan)
- {
- OIC_LOG(INFO, TAG, "scanning is already stopped");
- return CA_STATUS_OK;
- }
-
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
OIC_LOG(ERROR, TAG, "CALEClientStopScanImpl has failed");
}
}
- else
- {
- CALEClientSetScanFlag(false);
- }
if (isAttached)
{
return ret;
}
-void CALEClientSetScanFlag(bool flag)
-{
- ca_mutex_lock(g_scanMutex);
- g_isStartedScan = flag;
- ca_mutex_unlock(g_scanMutex);
-}
-
CAResult_t CALEClientStopScanImpl(JNIEnv *env, jobject callback)
{
OIC_LOG(DEBUG, TAG, "CALEClientStopScanImpl");
if (!jni_mid_getDefaultAdapter)
{
OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
return CA_STATUS_FAILED;
}
if (!jni_mid_stopLeScan)
{
OIC_LOG(ERROR, TAG, "stopLeScan: jni_mid_stopLeScan is null");
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
return CA_STATUS_FAILED;
}
if (!jni_obj_BTAdapter)
{
OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
return CA_STATUS_FAILED;
}
if ((*env)->ExceptionCheck(env))
{
OIC_LOG(ERROR, TAG, "stopLeScan has failed");
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
+ (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
return CA_STATUS_FAILED;
}
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
+ (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
return CA_STATUS_OK;
}
VERIFY_NON_NULL_VOID(object, TAG, "object is null");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
if (!g_deviceList)
{
OIC_LOG(ERROR, TAG, "gdevice_list is null");
-
- CALEClientSetScanFlag(false);
- if (CA_STATUS_OK != CALEClientStopScan())
- {
- OIC_LOG(ERROR, TAG, "CALEClientStopScan has failed");
- }
+ CALEClientStopScanWithInterval();
ca_mutex_unlock(g_deviceListMutex);
return CA_STATUS_FAILED;
}
}
- if (NULL == g_scanMutex)
- {
- g_scanMutex = ca_mutex_new();
- if (NULL == g_scanMutex)
- {
- OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
- return CA_STATUS_FAILED;
- }
- }
-
if (NULL == g_threadWriteCharacteristicMutex)
{
g_threadWriteCharacteristicMutex = ca_mutex_new();
}
}
+ if (NULL == g_threadScanIntervalMutex)
+ {
+ g_threadScanIntervalMutex = ca_mutex_new();
+ if (NULL == g_threadScanIntervalMutex)
+ {
+ OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+ return CA_STATUS_FAILED;
+ }
+ }
+
return CA_STATUS_OK;
}
ca_mutex_free(g_SendFinishMutex);
g_SendFinishMutex = NULL;
- ca_mutex_free(g_scanMutex);
- g_scanMutex = NULL;
-
ca_mutex_free(g_threadWriteCharacteristicMutex);
g_threadWriteCharacteristicMutex = NULL;
ca_mutex_free(g_threadSendStateMutex);
g_threadSendStateMutex = NULL;
+
+ ca_mutex_free(g_threadScanIntervalMutex);
+ g_threadScanIntervalMutex = NULL;
}
void CALEClientSetSendFinishFlag(bool flag)
g_threadWriteCharacteristicCond = ca_cond_new();
}
- CAResult_t ret = CALEClientStartScan();
+ CAResult_t ret = CALEClientStartScanWithInterval();
if (CA_STATUS_OK != ret)
{
- OIC_LOG(ERROR, TAG, "CALEClientStartScan has failed");
+ OIC_LOG(ERROR, TAG, "CALEClientStartScanWithInterval has failed");
return ret;
}
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
OIC_LOG(ERROR, TAG, "CALEClientDisconnectAll has failed");
}
- ret = CALEClientStopScan();
- if(CA_STATUS_OK != ret)
- {
- OIC_LOG(ERROR, TAG, "CALEClientStopScan has failed");
- }
+ CALEClientStopScanWithInterval();
ca_mutex_lock(g_threadMutex);
OIC_LOG(DEBUG, TAG, "signal - connection cond");
ca_cond_signal(g_deviceScanRetryDelayCond);
ca_mutex_unlock(g_deviceScanRetryDelayMutex);
+ ca_mutex_lock(g_threadScanIntervalMutex);
+ OIC_LOG(DEBUG, TAG, "signal - delay cond");
+ ca_cond_signal(g_threadScanIntervalCond);
+ ca_mutex_unlock(g_threadScanIntervalMutex);
+
ca_cond_free(g_deviceDescCond);
ca_cond_free(g_threadCond);
ca_cond_free(g_threadWriteCharacteristicCond);
ca_cond_free(g_deviceScanRetryDelayCond);
+ ca_cond_free(g_threadScanIntervalCond);
g_deviceDescCond = NULL;
g_threadCond = NULL;
g_threadWriteCharacteristicCond = NULL;
g_deviceScanRetryDelayCond = NULL;
+ g_threadScanIntervalCond = NULL;
if (isAttached)
{
}
}
-static jstring CALEClientGetAddressFromGatt(JNIEnv *env, jobject gatt)
-{
- OIC_LOG(DEBUG, TAG, "IN - CAManagerGetAddressFromGatt");
-
- VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
- VERIFY_NON_NULL_RET(gatt, TAG, "gatt is null", NULL);
-
- jmethodID jni_mid_getDevice = CAGetJNIMethodID(env, CLASSPATH_BT_GATT,
- "getDevice", METHODID_BT_DEVICE);
- if (!jni_mid_getDevice)
- {
- OIC_LOG(ERROR, TAG, "jni_mid_getDevice is null");
- return NULL;
- }
-
- jobject jni_obj_device = (*env)->CallObjectMethod(env, gatt, jni_mid_getDevice);
- if (!jni_obj_device)
- {
- OIC_LOG(ERROR, TAG, "jni_obj_device is null");
- return NULL;
- }
-
- jstring jni_address = CALEGetAddressFromBTDevice(env, jni_obj_device);
- if (!jni_address)
- {
- OIC_LOG(ERROR, TAG, "jni_address is null");
- return NULL;
- }
-
- OIC_LOG(DEBUG, TAG, "OUT - CAManagerGetAddressFromGatt");
- return jni_address;
-}
-
/*
* Class: org_iotivity_ca_jar_caleinterface
* Method: CALeGattConnectionStateChangeCallback
}
OIC_LOG_V(DEBUG, TAG, "CALeGattConnectionStateChangeCallback - address [%s]", address);
- CAResult_t res;
if (state_connected == newstate)
{
OIC_LOG(DEBUG, TAG, "LE is connected");
if (GATT_SUCCESS == status)
{
- res = CALEClientUpdateDeviceState(address, CA_LE_CONNECTION_STATE, STATE_CONNECTED);
+ CAResult_t res = CALEClientUpdateDeviceState(address,
+ CA_LE_CONNECTION_STATE,
+ STATE_CONNECTED);
(*env)->ReleaseStringUTFChars(env, jni_address, address);
if (CA_STATUS_OK != res)
{
{
OIC_LOG(DEBUG, TAG, "LE is disconnected");
- res = CALEClientUpdateDeviceState(address, CA_LE_CONNECTION_STATE, STATE_DISCONNECTED);
+ CAResult_t res = CALEClientUpdateDeviceState(address,
+ CA_LE_CONNECTION_STATE,
+ STATE_DISCONNECTED);
(*env)->ReleaseStringUTFChars(env, jni_address, address);
if (CA_STATUS_OK != res)
{
OIC_LOG(ERROR, TAG, "CALEClientGattClose has failed");
}
- if (GATT_ERROR == status)
+ if (CALECheckConnectionStateValue(status))
{
- // when we get GATT ERROR(0x85), gatt connection can be called again.
- OIC_LOG(INFO, TAG, "retry gatt connect");
-
- jstring leAddress = CALEClientGetAddressFromGatt(env, gatt);
- if (!leAddress)
- {
- OIC_LOG(ERROR, TAG, "CALEClientGetAddressFromGatt has failed");
- goto error_exit;
- }
-
- jobject btObject = CALEGetRemoteDevice(env, leAddress);
- if (!btObject)
- {
- OIC_LOG(ERROR, TAG, "CALEGetRemoteDevice has failed");
- goto error_exit;
- }
-
- jobject newGatt = CALEClientConnect(env, btObject, JNI_TRUE);
- if (!newGatt)
- {
- OIC_LOG(ERROR, TAG, "CALEClientConnect has failed");
- goto error_exit;
- }
-
- return;
+ // this state is unexpected reason to disconnect
+ // if the reason is suitable, connection logic of the device will be destroyed.
+ OIC_LOG(INFO, TAG, "connection logic destroy");
+ goto error_exit;
}
else
{
- if (CALECheckConnectionStateValue(status))
- {
- // this state is unexpected reason to disconnect
- // if the reason is suitable, connection logic of the device will be destroyed.
- OIC_LOG(INFO, TAG, "connection logic destroy");
- goto error_exit;
- }
- else
- {
- // other reason except for gatt_success is expected to running
- // background connection in BT platform.
- OIC_LOG(INFO, TAG, "unknown status or manual disconnected state");
- CALEClientUpdateSendCnt(env);
- return;
- }
+ // other reason except for gatt_success is expected to running
+ // background connection in BT platform.
+ OIC_LOG(INFO, TAG, "unknown status or manual disconnected state");
+ CALEClientUpdateSendCnt(env);
+ return;
}
if (g_sendBuffer)
} CALEState_t;
/**
+ * BLE Scanning State.
+ */
+typedef enum
+{
+ BLE_SCAN_ENABLE = 0, /**< BLE scan is working */
+ BLE_SCAN_DISABLE /**< BLE scan is not working */
+} CALEScanState_t;
+
+/**
* Callback to be notified on reception of any data from remote devices.
* @param[in] address MAC address of remote device.
* @param[in] data Data received from remote device.
CAResult_t CALEClientStopScan();
/**
- * set ble scanning flag.
- * @param[in] flag scan flag.
- */
-void CALEClientSetScanFlag(bool flag);
-
-/**
* stop scan (implement).
* @param[in] env JNI interface pointer.
* @param[in] callback callback to receive device object by scanning.
*/
CAResult_t CALEClientDirectConnect(JNIEnv *env, jobject bluetoothDevice, jboolean autoconnect);
+/**
+ * set new interval time and working count.
+ * @param[in] intervalTime interval time(Seconds).
+ * @param[in] workingCount working count for selected interval time.
+ */
+void CALEClientSetScanInterval(int32_t intervalTime, int32_t workingCount);
+
+/**
+ * restart scanning with new interval time and working count.
+ * @param[in] intervalTime interval time(Seconds).
+ * @param[in] workingCount working count for selected interval time.
+ */
+void CALERestartScanWithInterval(int32_t intervalTime, int32_t workingCount);
+
+/**
+ * start LE scanning logic with interval time and working count.
+ * @return ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CALEClientStartScanWithInterval();
+
+/**
+ * stop LE scanning logic with interval time and cycle.
+ */
+void CALEClientStopScanWithInterval();
+
#ifdef __cplusplus
} /* extern "C" */
#endif
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
OIC_LOG(ERROR, TAG, "CALEServerRemoveAllDevices has failed");
}
- CALEClientSetScanFlag(false);
-
CANetworkStatus_t newStatus = CA_INTERFACE_DOWN;
g_bleDeviceStateChangedCallback(newStatus);
}
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
if (!jni_mid_getDefaultAdapter)
{
OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null");
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
return JNI_FALSE;
}
if (!jni_obj_BTAdapter)
{
OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null");
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
return JNI_FALSE;
}
if (!jni_mid_isEnable)
{
OIC_LOG(ERROR, TAG, "jni_mid_isEnable is null");
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
+ (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
return JNI_FALSE;
}
jboolean jni_isEnable = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter, jni_mid_isEnable);
OIC_LOG_V(DEBUG, TAG, "adapter state is %d", jni_isEnable);
+ (*env)->DeleteLocalRef(env, jni_cid_BTAdapter);
+ (*env)->DeleteLocalRef(env, jni_obj_BTAdapter);
return jni_isEnable;
}
/**
* Callback to notify any error in LE adapter.
*/
-static CABLEErrorHandleCallback g_serverErrorCallback;
+static CABLEErrorHandleCallback g_serverErrorCallback = NULL;
/**
* To keep the state of GATT server if started or not.
// Kill g main loops and kill threads
g_main_loop_quit(g_eventLoop);
}
+ g_eventLoop = NULL;
}
else
{
return CA_STATUS_FAILED;
}
- bt_gatt_server_h server;
-
- ret = bt_gatt_server_create(&server);
- if (0 != ret)
- {
- OIC_LOG_V(ERROR, TAG, "bt_gatt_server_create failed with ret[%s]",
- CALEGetErrorMsg(ret));
- return CA_STATUS_FAILED;
- }
-
- if (NULL != g_gattServer)
+ if (!g_gattServer)
{
- OICFree(g_gattServer);
- g_gattServer = NULL;
+ OIC_LOG(DEBUG, TAG, "g_gattServer is NULL. create gatt server..");
+ ret = bt_gatt_server_create(&g_gattServer);
+ if (0 != ret)
+ {
+ OIC_LOG_V(ERROR, TAG, "bt_gatt_server_create failed with ret[%s]",
+ CALEGetErrorMsg(ret));
+ return CA_STATUS_FAILED;
+ }
}
- g_gattServer = server;
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
CALEGetErrorMsg(ret));
return CA_STATUS_FAILED;
}
+ g_gattServer = NULL;
ret = bt_gatt_server_deinitialize();
if (0 != ret)
OIC_LOG_V(DEBUG, TAG, "service uuid %s", serviceUUID);
- bt_gatt_h service = NULL;
bt_gatt_service_type_e type = BT_GATT_SERVICE_TYPE_PRIMARY;
- int ret = bt_gatt_service_create(serviceUUID, type, &service);
+ ca_mutex_lock(g_leServiceMutex);
+ int ret = bt_gatt_service_create(serviceUUID, type, &g_gattSvcPath);
if (0 != ret)
{
+ ca_mutex_unlock(g_leServiceMutex);
OIC_LOG_V(ERROR, TAG, "bt_gatt_service_create failed with ret [%s]",
- CALEGetErrorMsg(ret));
+ CALEGetErrorMsg(ret));
return CA_STATUS_FAILED;
}
+ ca_mutex_unlock(g_leServiceMutex);
- if (NULL != service)
+ if (g_gattSvcPath)
{
- OIC_LOG_V(DEBUG, TAG, "ServicePath obtained is %s", (char *)service);
-
- ca_mutex_lock(g_leServiceMutex);
-
- if (NULL != g_gattSvcPath)
- {
- OICFree(g_gattSvcPath);
- g_gattSvcPath = NULL;
- }
- g_gattSvcPath = service;
-
- ca_mutex_unlock(g_leServiceMutex);
+ OIC_LOG_V(DEBUG, TAG, "ServicePath obtained is %s", (char *)g_gattSvcPath);
}
OIC_LOG(DEBUG, TAG, "OUT");
int permissions = BT_GATT_PERMISSION_READ | BT_GATT_PERMISSION_WRITE;
int properties;
- if(read)
+ if (read)
{
properties = BT_GATT_PROPERTY_NOTIFY | BT_GATT_PROPERTY_READ;
}
properties = BT_GATT_PROPERTY_WRITE | BT_GATT_PROPERTY_READ;
}
- bt_gatt_h charPath;
+ bt_gatt_h charPath = NULL;
int ret = bt_gatt_characteristic_create(charUUID, permissions, properties, charValue,
charValueLen, &charPath);
&descriptor);
if (0 != ret)
{
+ ca_mutex_unlock(g_leCharacteristicMutex);
OIC_LOG_V(ERROR, TAG,
"bt_gatt_descriptor_create failed with ret[%s]",
CALEGetErrorMsg(ret));
ret = bt_gatt_characteristic_add_descriptor(charPath, descriptor);
if (0 != ret)
{
+ ca_mutex_unlock(g_leCharacteristicMutex);
OIC_LOG_V(ERROR, TAG,
"bt_gatt_characteristic_add_descriptor failed with ret[%s]",
CALEGetErrorMsg(ret));
return CA_STATUS_FAILED;
}
- if (NULL != g_gattReadCharPath)
- {
- OICFree(g_gattReadCharPath);
- g_gattReadCharPath = NULL;
- }
g_gattReadCharPath = charPath;
-
}
else
{
- if (NULL != g_gattWriteCharPath)
- {
- OICFree(g_gattWriteCharPath);
- g_gattWriteCharPath = NULL;
- }
g_gattWriteCharPath = charPath;
}
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;
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:
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)
{
}
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;
}
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,
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)
{
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
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)
{
CAGetResponseInfoFromPDU(pdu, resInfo, endpoint);
requestInfo->method = CA_GET;
+ requestInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu->hdr, pdu->length);
requestInfo->info.resourceUri = OICStrdup(resInfo->info.resourceUri);
// after copying the resource uri, destroy response info.
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");
VERIFY_NON_NULL(sendData, TAG, "sendData");
VERIFY_NON_NULL(blockData, TAG, "blockData");
- CABlockDataID_t* blockDataID;
- if(sendData->requestInfo)
- {
- blockDataID = CACreateBlockDatablockId(
- (CAToken_t)sendData->requestInfo->info.token,
- sendData->requestInfo->info.tokenLength,
- sendData->remoteEndpoint->port);
- }
- else if(sendData->responseInfo)
- {
- blockDataID = CACreateBlockDatablockId(
- (CAToken_t)sendData->responseInfo->info.token,
- sendData->responseInfo->info.tokenLength,
- sendData->remoteEndpoint->port);
- }
- else
+ if (sendData->responseInfo)
{
- OIC_LOG(ERROR, TAG, "sendData doesn't have requestInfo or responseInfo");
- return CA_STATUS_FAILED;
- }
-
- if (NULL == blockDataID || blockDataID->idLength < 1)
- {
- OIC_LOG(ERROR, TAG, "blockId is null");
- CADestroyBlockID(blockDataID);
- return CA_STATUS_FAILED;
- }
-
- ca_mutex_lock(g_context.blockDataListMutex);
-
- size_t len = u_arraylist_length(g_context.dataList);
- for (size_t i = 0; i < len; i++)
- {
- CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
- if (!currData)
+ CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
+ (CAToken_t)sendData->responseInfo->info.token,
+ sendData->responseInfo->info.tokenLength,
+ sendData->remoteEndpoint->port);
+ if (NULL == blockDataID || blockDataID->idLength < 1)
{
- continue;
+ OIC_LOG(ERROR, TAG, "blockId is null");
+ CADestroyBlockID(blockDataID);
+ return CA_STATUS_FAILED;
}
- if (sendData->requestInfo) // sendData is requestMessage
- {
- OIC_LOG(DEBUG, TAG, "Send request");
- if (NULL != currData->blockDataId
- && NULL != currData->blockDataId->id
- && currData->blockDataId->idLength > 0
- && NULL != sendData->requestInfo->info.token)
- {
- if (CABlockidMatches(currData, blockDataID))
- {
- OIC_LOG(ERROR, TAG, "already sent");
- continue;
- }
- }
- }
- else if (sendData->responseInfo) // sendData is responseMessage
+ CABlockData_t *storedData = CAGetBlockDataFromBlockDataList(blockDataID);
+ if (storedData)
{
- OIC_LOG(DEBUG, TAG, "Send response");
- if (NULL != currData->blockDataId
- && NULL != currData->blockDataId->id
- && currData->blockDataId->idLength > 0
- && NULL != sendData->responseInfo->info.token)
+ OIC_LOG(DEBUG, TAG, "Send response about the received block request.");
+ if (storedData->sentData)
{
- if (CABlockidMatches(currData, blockDataID))
- {
- // set sendData
- if (NULL != currData->sentData)
- {
- OIC_LOG(DEBUG, TAG, "init block number");
- CADestroyDataSet(currData->sentData);
- }
- currData->sentData = CACloneCAData(sendData);
- *blockData = currData;
- ca_mutex_unlock(g_context.blockDataListMutex);
- CADestroyBlockID(blockDataID);
- return CA_STATUS_OK;
- }
+ OIC_LOG(DEBUG, TAG, "init block number");
+ CADestroyDataSet(storedData->sentData);
}
+ storedData->sentData = CACloneCAData(sendData);
+ *blockData = storedData;
+ CADestroyBlockID(blockDataID);
+ return CA_STATUS_OK;
}
- else
- {
- OIC_LOG(ERROR, TAG, "no CAInfo data");
- continue;
- }
+ CADestroyBlockID(blockDataID);
}
- ca_mutex_unlock(g_context.blockDataListMutex);
-
- CADestroyBlockID(blockDataID);
return CA_STATUS_FAILED;
}
{
OIC_LOG(DEBUG, TAG, "CAStartListeningServer");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CAStopListeningServer");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CAStartDiscoveryServer");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CARegisterHandler");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
OIC_LOG(DEBUG, TAG, "CA is not initialized");
return;
{
OIC_LOG(DEBUG, TAG, "CARegisterDTLSHandshakeCallback");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CARegisterDTLSCredentialsHandler");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CARegisterDTLSX509CredentialsHandler");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CARegisterDTLSCrlHandler");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CAGetNetworkInformation");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CASendRequest");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CASendResponse");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG_V(DEBUG, TAG, "Selected network : %d", interestedNetwork);
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG_V(DEBUG, TAG, "unselected network : %d", nonInterestedNetwork);
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
static void CARegisterCallback(CAConnectivityHandler_t handler)
{
- if(handler.startAdapter == NULL ||
+ if (handler.startAdapter == NULL ||
handler.startListenServer == NULL ||
handler.stopListenServer == NULL ||
handler.startDiscoveryServer == NULL ||
{
void* ptrType = u_arraylist_get(list, i);
- if(NULL == ptrType)
+ if (NULL == ptrType)
{
continue;
}
int index = CAGetAdapterIndex(connType);
if (0 > index)
- if (-1 == index)
{
- OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+ OIC_LOG(ERROR, TAG, "unknown connectivity type!");
continue;
}
}
OIC_LOG_V(DEBUG, TAG, "address : %s", ep->addr);
- CAResult_t result;
- if(CA_RESPONSE_DATA == dataType)
+ if (CA_RESPONSE_DATA == dataType)
{
CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
if (!resInfo)
return NULL;
}
- result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
+ CAResult_t result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
if (CA_STATUS_OK != result)
{
OIC_LOG(ERROR, TAG, "CAGetResponseInfoFromPDU Failed");
return NULL;
}
- result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
+ CAResult_t result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
if (CA_STATUS_OK != result)
{
OIC_LOG(ERROR, TAG, "CAGetRequestInfoFromPDU failed");
coap_pdu_t *pdu = NULL;
CAInfo_t *info = NULL;
coap_list_t *options = NULL;
- coap_transport_type transport;
+ coap_transport_type transport = coap_udp;
CAResult_t res = CA_SEND_FAILED;
if (NULL != data->requestInfo)
{
coap_pdu_t *pdu = NULL;
CAInfo_t *info = NULL;
coap_list_t *options = NULL;
- coap_transport_type transport;
+ coap_transport_type transport = coap_udp;
if (SEND_TYPE_UNICAST == type)
{
OIC_LOG(DEBUG,TAG,"Unicast message");
+
#ifdef ROUTING_GATEWAY
/*
* When forwarding a packet, do not attempt retransmission as its the responsibility of
return NULL;
}
- if(CA_REQUEST_DATA == dataType)
+ if (CA_REQUEST_DATA == dataType)
{
// clone request info
CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
- if(!request)
+ if (!request)
{
OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
goto exit;
cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
cadata->requestInfo = request;
}
- else if(CA_RESPONSE_DATA == dataType)
+ else if (CA_RESPONSE_DATA == dataType)
{
// clone response info
CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
#ifdef SINGLE_THREAD
CAResult_t result = CAProcessSendData(data);
- if(CA_STATUS_OK != result)
+ if (CA_STATUS_OK != result)
{
OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
CADestroyData(data, sizeof(CAData_t));
{
// send block data
CAResult_t res = CASendBlockWiseData(data);
- if(CA_NOT_SUPPORTED == res)
+ if (CA_NOT_SUPPORTED == res)
{
OIC_LOG(DEBUG, TAG, "normal msg will be sent");
CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
static void CALogPayloadInfo(CAInfo_t *info)
{
- if(info)
+ if (info)
{
if (info->options)
{
#define TAG "OIC_CA_PRTCL_MSG"
-#define CA_BUFSIZE (128)
#define CA_PDU_MIN_SIZE (4)
#define CA_ENCODE_BUFFER_SIZE (4)
#endif
{
OIC_LOG_V(DEBUG, TAG, "msgID is %d", info->messageId);
- uint16_t message_id;
+ uint16_t message_id = 0;
if (0 == info->messageId)
{
/* initialize message id */
}
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) :
uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
{
uint32_t count = 0;
- coap_opt_t *option;
+ coap_opt_t *option = NULL;
while ((option = coap_option_next(&opt_iter)))
{
}
}
- coap_opt_t *option;
+ coap_opt_t *option = NULL;
char optionResult[CA_MAX_URI_LENGTH] = {0};
uint32_t idx = 0;
uint32_t optionLength = 0;
VERIFY_NON_NULL(outInfo, TAG, "outInfo");
VERIFY_NON_NULL(endpoint, TAG, "endpoint");
- coap_transport_type transport;
+ coap_transport_type transport = coap_udp;
#ifdef WITH_TCP
if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
{
transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu_hdr)[0] >> 4);
}
- else
#endif
- {
- transport = coap_udp;
- }
unsigned char* token = NULL;
unsigned int token_length = 0;
// should remain that way so a 0 byte of length 1 is inserted.
len = 1;
option[0]=0;
- } else {
+ }
+ else
+ {
memcpy(option, data, len);
option[len] = '\0';
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
+#endif
#include "caqueueingthread.h"
#include "oic_malloc.h"
if (NULL == thread)
{
OIC_LOG(ERROR, TAG, "thread data passing error!!");
-
return;
}
thread->isStop = true;
thread->threadTask = task;
thread->destroy = destroy;
- if(NULL == thread->dataQueue || NULL == thread->threadMutex || NULL == thread->threadCond)
+ if (NULL == thread->dataQueue || NULL == thread->threadMutex || NULL == thread->threadCond)
+ {
goto ERROR_MEM_FAILURE;
+ }
return CA_STATUS_OK;
- ERROR_MEM_FAILURE:
- if(thread->dataQueue)
+
+ERROR_MEM_FAILURE:
+ if (thread->dataQueue)
{
u_queue_delete(thread->dataQueue);
thread->dataQueue = NULL;
}
- if(thread->threadMutex)
+ if (thread->threadMutex)
{
ca_mutex_free(thread->threadMutex);
thread->threadMutex = NULL;
}
- if(thread->threadCond)
+ if (thread->threadCond)
{
ca_cond_free(thread->threadCond);
thread->threadCond = NULL;
}
return CA_MEMORY_ALLOC_FAILED;
-
}
CAResult_t CAQueueingThreadStart(CAQueueingThread_t *thread)
u_queue_message_t *message = u_queue_get_element(thread->dataQueue);
// free
- if(NULL != message)
+ if (NULL != message)
{
if (NULL != thread->destroy)
{
#include <string.h>
#ifndef SINGLE_THREAD
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
-#include <time.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
+#if HAVE_SYS_TIMEB_H
+#include <sys/timeb.h>
+#endif
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif
+#endif
#if defined(__ANDROID__)
#include <linux/time.h>
#include "caremotehandler.h"
#include "caprotocolmessage.h"
#include "oic_malloc.h"
+#include "ocrandom.h"
#include "logger.h"
#define TAG "OIC_CA_RETRANS"
} CARetransmissionData_t;
static const uint64_t USECS_PER_SEC = 1000000;
+static const uint64_t MSECS_PER_SEC = 1000;
/**
* @brief getCurrent monotonic time
*/
static uint64_t CAGetTimeoutValue()
{
- return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * (random() & 0xFF)) >> 8)) *
+#ifdef HAVE_SRANDOM
+ return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * OCGetRandomByte()) >> 8)) *
+ (uint64_t) 1000;
+#else
+ return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * OCGetRandomByte()) >> 8)) *
(uint64_t) 1000;
+#endif
}
CAResult_t CARetransmissionStart(CARetransmission_t *context)
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
currentTime = ts.tv_sec * USECS_PER_SEC + ts.tv_nsec / 1000;
+#elif defined(_WIN32)
+ struct __timeb64 tb;
+ _ftime64_s(&tb);
+ currentTime = tb.time * USECS_PER_SEC + tb.millitm * MSECS_PER_SEC;
#else
struct timeval tv;
gettimeofday(&tv, NULL);
target_files += [ os.path.join(src_dir,
'linux/caipnwmonitor.c') ]
+if target_os in ['msys_nt']:
+ target_files += [ os.path.join(src_dir, 'windows/caipnwmonitor.c') ]
+
# The list of BLE adapter source files is a combination of both the
# common and target-specific source file lists.
env.AppendUnique(CA_SRC = common_files + target_files)
caglobals.ip.nm.numIfItems = 0;
for (size_t i = 0; i < interfaces; i++)
{
- CAResult_t result = CA_STATUS_OK;
struct ifreq* item = &ifr[i];
char *name = item->ifr_name;
struct sockaddr_in *sa4 = (struct sockaddr_in *)&item->ifr_addr;
}
// Add IPv4 interface
- result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET, ipv4addr, flags);
+ CAResult_t result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET, ipv4addr, flags);
if (CA_STATUS_OK != result)
{
goto exit;
return CA_STATUS_FAILED;
}
- JNIEnv* env;
+ JNIEnv* env = NULL;
if ((*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
{
OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
eps[j].flags = CA_IPV4;
eps[j].adapter = CA_ADAPTER_IP;
- eps[j].interface = 0;
+ eps[j].ifindex = 0;
eps[j].port = caglobals.ip.u4.port;
j++;
}
eps[j].flags = CA_IPV4;
eps[j].adapter = CA_ADAPTER_IP;
- eps[j].interface = 0;
+ eps[j].ifindex = 0;
eps[j].port = caglobals.ip.u4.port;
j++;
}
CAResult_t CAStartIP()
{
+ // Specific the port number received from application.
+ caglobals.ip.u6.port = caglobals.ports.udp.u6;
+ caglobals.ip.u6s.port = caglobals.ports.udp.u6s;
+ caglobals.ip.u4.port = caglobals.ports.udp.u4;
+ caglobals.ip.u4s.port = caglobals.ports.udp.u4s;
+
CAIPStartNetworkMonitor();
#ifdef SINGLE_THREAD
uint16_t unicastPort = 55555;
-/*****************************************************************j
+/* ****************************************************************
*
* Copyright 2014 Samsung Electronics All Rights Reserved.
*
#endif
#include <sys/types.h>
+#if !defined(_WIN32)
#include <sys/socket.h>
+#endif
+
+#if defined(_WIN32)
+#include <assert.h>
+#include <winsock2.h>
+#include <ws2def.h>
+#include <mswsock.h>
+#include <ws2tcpip.h>
+#endif
+
#include <stdio.h>
+#if !defined(_MSC_VER)
#include <unistd.h>
+#endif //!defined(_MSC_VER)
#include <sys/types.h>
#include <fcntl.h>
+#if !defined(_WIN32)
#include <sys/select.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <net/if.h>
+#endif
#include <errno.h>
#ifdef __linux__
#include <linux/netlink.h>
#include "camutex.h"
#include "oic_malloc.h"
#include "oic_string.h"
+#include "platform_features.h"
+
+#define USE_IP_MREQN
+#if defined(_WIN32)
+#undef USE_IP_MREQN
+#endif
/*
* Logging tag for module name
NULL
};
-static CAIPPacketReceivedCallback g_packetReceivedCallback = NULL;
+#if defined (_WIN32)
+#define IFF_UP_RUNNING_FLAGS (IFF_UP)
+ char* caips_get_error(){
+ static char buffer[32];
+ snprintf(buffer, 32, "%i", WSAGetLastError());
+ return buffer;
+ }
+#define CAIPS_GET_ERROR \
+ caips_get_error()
+#else
+#define IFF_UP_RUNNING_FLAGS (IFF_UP|IFF_RUNNING)
+
+#define CAIPS_GET_ERROR \
+ strerror(errno)
+#endif
static CAIPErrorHandleCallback g_ipErrorHandler = NULL;
-static void CAHandleNetlink();
+static CAIPPacketReceivedCallback g_packetReceivedCallback = NULL;
+
static void CAFindReadyMessage();
+#if !defined(WSA_WAIT_EVENT_0)
static void CASelectReturned(fd_set *readFds, int ret);
+#else
+static void CAEventReturned(CASocketFd_t socket);
+#endif
static void CAProcessNewInterface(CAInterface_t *ifchanged);
-static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags);
+static CAResult_t CAReceiveMessage(CASocketFd_t fd, CATransportFlags_t flags);
-#define SET(TYPE, FDS) \
- if (caglobals.ip.TYPE.fd != -1) \
- { \
- FD_SET(caglobals.ip.TYPE.fd, FDS); \
- }
+static void CAReceiveHandler(void *data)
+{
+ (void)data;
-#define ISSET(TYPE, FDS, FLAGS) \
- if (caglobals.ip.TYPE.fd != -1 && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
- { \
- fd = caglobals.ip.TYPE.fd; \
- flags = FLAGS; \
+ while (!caglobals.ip.terminate)
+ {
+ CAFindReadyMessage();
}
+}
+
+#if !defined(WSA_WAIT_EVENT_0)
#define CLOSE_SOCKET(TYPE) \
- if (caglobals.ip.TYPE.fd != -1) \
+ if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
{ \
close(caglobals.ip.TYPE.fd); \
- caglobals.ip.TYPE.fd = -1; \
+ caglobals.ip.TYPE.fd = OC_INVALID_SOCKET; \
}
-void CADeInitializeIPGlobals()
-{
- CLOSE_SOCKET(u6);
- CLOSE_SOCKET(u6s);
- CLOSE_SOCKET(u4);
- CLOSE_SOCKET(u4s);
- CLOSE_SOCKET(m6);
- CLOSE_SOCKET(m6s);
- CLOSE_SOCKET(m4);
- CLOSE_SOCKET(m4s);
-
- if (caglobals.ip.netlinkFd != -1)
- {
- close(caglobals.ip.netlinkFd);
- caglobals.ip.netlinkFd = -1;
+#define SET(TYPE, FDS) \
+ if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
+ { \
+ FD_SET(caglobals.ip.TYPE.fd, FDS); \
}
-}
-
-static void CAReceiveHandler(void *data)
-{
- (void)data;
- while (!caglobals.ip.terminate)
- {
- CAFindReadyMessage();
+#define ISSET(TYPE, FDS, FLAGS) \
+ if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
+ { \
+ fd = caglobals.ip.TYPE.fd; \
+ flags = FLAGS; \
}
-}
+
static void CAFindReadyMessage()
{
SET(m6s, &readFds)
SET(m4, &readFds)
SET(m4s, &readFds)
+
if (caglobals.ip.shutdownFds[0] != -1)
{
FD_SET(caglobals.ip.shutdownFds[0], &readFds);
}
- if (caglobals.ip.netlinkFd != -1)
+ if (caglobals.ip.netlinkFd != OC_INVALID_SOCKET)
{
FD_SET(caglobals.ip.netlinkFd, &readFds);
}
OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
return;
}
+
if (ret <= 0)
{
if (ret < 0)
{
- OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
+ OIC_LOG_V(FATAL, TAG, "select error %s", CAIPS_GET_ERROR);
}
return;
}
static void CASelectReturned(fd_set *readFds, int ret)
{
(void)ret;
- int fd = -1;
+ CASocketFd_t fd = OC_INVALID_SOCKET;
CATransportFlags_t flags = CA_DEFAULT_FLAGS;
while (!caglobals.ip.terminate)
else ISSET(m6s, readFds, CA_MULTICAST | CA_IPV6 | CA_SECURE)
else ISSET(m4, readFds, CA_MULTICAST | CA_IPV4)
else ISSET(m4s, readFds, CA_MULTICAST | CA_IPV4 | CA_SECURE)
- else if (FD_ISSET(caglobals.ip.netlinkFd, readFds))
+ else if ((caglobals.ip.netlinkFd != OC_INVALID_SOCKET) && FD_ISSET(caglobals.ip.netlinkFd, readFds))
{
CAInterface_t *ifchanged = CAFindInterfaceChange();
if (ifchanged)
{
break;
}
-
(void)CAReceiveMessage(fd, flags);
FD_CLR(fd, readFds);
}
}
-static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
+#else // if defined(WSA_WAIT_EVENT_0)
+
+#define CLOSE_SOCKET(TYPE) \
+ if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
+ { \
+ closesocket(caglobals.ip.TYPE.fd); \
+ caglobals.ip.TYPE.fd = OC_INVALID_SOCKET; \
+ }
+
+#define PUSH_HANDLE(HANDLE, ARRAY, INDEX) \
+{ \
+ ARRAY[INDEX] = HANDLE; \
+ INDEX++; \
+}
+
+// Turn handle into WSAEvent and push to ARRAY
+#define PUSH_SOCKET(SOCKET, ARRAY, INDEX) \
+ if (SOCKET != OC_INVALID_SOCKET) \
+ { \
+ WSAEVENT NewEvent; \
+ NewEvent = WSACreateEvent(); \
+ if (WSA_INVALID_EVENT != NewEvent) \
+ { \
+ if (0 != WSAEventSelect(SOCKET, NewEvent, FD_READ)) \
+ { \
+ OIC_LOG_V(ERROR, TAG, "WSAEventSelect failed 0x%08x ", WSAGetLastError()); \
+ if (!WSACloseEvent(NewEvent)) \
+ { \
+ OIC_LOG_V(ERROR, TAG, "WSACloseEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
+ } \
+ } \
+ else \
+ { \
+ PUSH_HANDLE(NewEvent, ARRAY, INDEX); \
+ } \
+ } \
+ else \
+ { \
+ OIC_LOG_V(ERROR, TAG, "WSACreateEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
+ }\
+ }
+
+#define INSERT_SOCKET(FD, ARRAY, INDEX) \
+ { \
+ if (OC_INVALID_SOCKET != FD) \
+ { \
+ ARRAY[INDEX] = FD; \
+ } \
+ }
+
+
+// Inserts the socket into the SOCKET_ARRAY and pushes the socket event into EVENT_ARRAY
+#define PUSH_IP_SOCKET(TYPE, EVENT_ARRAY, SOCKET_ARRAY, INDEX) \
+ { \
+ if (OC_INVALID_SOCKET != caglobals.ip.TYPE.fd) \
+ { \
+ INSERT_SOCKET(caglobals.ip.TYPE.fd, SOCKET_ARRAY, INDEX); \
+ PUSH_SOCKET(caglobals.ip.TYPE.fd, EVENT_ARRAY, INDEX); \
+ } \
+ }
+
+#define IS_MATCHING_IP_SOCKET(TYPE, SOCKET, FLAGS) \
+ if ((caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) && (caglobals.ip.TYPE.fd == SOCKET)) \
+ { \
+ fd = caglobals.ip.TYPE.fd; \
+ flags = FLAGS; \
+ }
+
+#define EVENT_ARRAY_SIZE 10
+
+static void CAFindReadyMessage()
{
- char recvBuffer[COAP_MAX_PDU_SIZE];
+ CASocketFd_t socketArray[EVENT_ARRAY_SIZE];
+ HANDLE eventArray[EVENT_ARRAY_SIZE];
+ int arraySize = 0;
+ int eventIndex;
+
+ // socketArray and eventArray should have same number of elements
+ OC_STATIC_ASSERT(_countof(socketArray) == _countof(eventArray), "Arrays should have same number of elements");
+
+ PUSH_IP_SOCKET(u6, eventArray, socketArray, arraySize);
+ PUSH_IP_SOCKET(u6s, eventArray, socketArray, arraySize);
+ PUSH_IP_SOCKET(u4, eventArray, socketArray, arraySize);
+ PUSH_IP_SOCKET(u4s, eventArray, socketArray, arraySize);
+ PUSH_IP_SOCKET(m6, eventArray, socketArray, arraySize);
+ PUSH_IP_SOCKET(m6s, eventArray, socketArray, arraySize);
+ PUSH_IP_SOCKET(m4, eventArray, socketArray, arraySize);
+ PUSH_IP_SOCKET(m4s, eventArray, socketArray, arraySize);
+
+ if (-1 != caglobals.ip.shutdownEvent)
+ {
+ INSERT_SOCKET(OC_INVALID_SOCKET, socketArray, arraySize);
+ PUSH_HANDLE(caglobals.ip.shutdownEvent, eventArray, arraySize);
+ }
+
+ /** @todo Support netlink events */
+
+ // Should not have overflowed buffer
+ assert(arraySize <= (_countof(socketArray)));
+
+ // Timeout is unnecessary on Windows
+ assert(-1 == caglobals.ip.selectTimeout);
+
+ while (!caglobals.ip.terminate)
+ {
+ int ret = WSAWaitForMultipleEvents(arraySize, eventArray, FALSE, WSA_INFINITE, FALSE);
+
+ switch (ret)
+ {
+ case WSA_WAIT_FAILED:
+ OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_FAILED 0x%08x", WSAGetLastError());
+ break;
+ case WSA_WAIT_IO_COMPLETION:
+ OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_IO_COMPLETION 0x%08x", WSAGetLastError());
+ break;
+ case WSA_WAIT_TIMEOUT:
+ OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_TIMEOUT 0x%08x", WSAGetLastError());
+ break;
+ default:
+ eventIndex = ret - WSA_WAIT_EVENT_0;
+ if ((eventIndex >= 0) && (eventIndex < arraySize))
+ {
+ if (false == WSAResetEvent(eventArray[eventIndex]))
+ {
+ OIC_LOG_V(ERROR, TAG, "WSAResetEvent failed 0x%08x", WSAGetLastError());
+ }
+
+ // Break out if shutdownEvent is triggered
+ if ((caglobals.ip.shutdownEvent != -1) &&
+ (caglobals.ip.shutdownEvent == eventArray[eventIndex]))
+ {
+ break;
+ }
+ CAEventReturned(socketArray[eventIndex]);
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents failed 0x%08x", WSAGetLastError());
+ }
+ break;
+ }
+
+ }
+
+ while (arraySize > 0)
+ {
+ arraySize--;
+ if (!WSACloseEvent(eventArray[arraySize]))
+ {
+ OIC_LOG_V(ERROR, TAG, "WSACloseEvent (Index %i) failed 0x%08x", arraySize, WSAGetLastError());
+ }
+ }
+
+ if (caglobals.ip.terminate)
+ {
+ caglobals.ip.shutdownEvent = -1;
+ WSACleanup();
+ }
+}
+
+static void CAEventReturned(CASocketFd_t socket)
+{
+ CASocketFd_t fd = OC_INVALID_SOCKET;
+ CATransportFlags_t flags = CA_DEFAULT_FLAGS;
+
+ while (!caglobals.ip.terminate)
+ {
+ IS_MATCHING_IP_SOCKET(u6, socket, CA_IPV6)
+ else IS_MATCHING_IP_SOCKET(u6s, socket, CA_IPV6 | CA_SECURE)
+ else IS_MATCHING_IP_SOCKET(u4, socket, CA_IPV4)
+ else IS_MATCHING_IP_SOCKET(u4s, socket, CA_IPV4 | CA_SECURE)
+ else IS_MATCHING_IP_SOCKET(m6, socket, CA_MULTICAST | CA_IPV6)
+ else IS_MATCHING_IP_SOCKET(m6s, socket, CA_MULTICAST | CA_IPV6 | CA_SECURE)
+ else IS_MATCHING_IP_SOCKET(m4, socket, CA_MULTICAST | CA_IPV4)
+ else IS_MATCHING_IP_SOCKET(m4s, socket, CA_MULTICAST | CA_IPV4 | CA_SECURE)
+ else
+ {
+ break;
+ }
+ (void)CAReceiveMessage(socket, flags);
+ // We will never get more than one match per socket, so always break.
+ break;
+ }
+}
+
+#endif
+
+void CADeInitializeIPGlobals()
+{
+ CLOSE_SOCKET(u6);
+ CLOSE_SOCKET(u6s);
+ CLOSE_SOCKET(u4);
+ CLOSE_SOCKET(u4s);
+ CLOSE_SOCKET(m6);
+ CLOSE_SOCKET(m6s);
+ CLOSE_SOCKET(m4);
+ CLOSE_SOCKET(m4s);
+
+ if (caglobals.ip.netlinkFd != OC_INVALID_SOCKET)
+ {
+#ifdef _WIN32
+ closesocket(caglobals.ip.netlinkFd);
+#else
+ close(caglobals.ip.netlinkFd);
+#endif
+ caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
+ }
+}
+
+static CAResult_t CAReceiveMessage(CASocketFd_t fd, CATransportFlags_t flags)
+{
+ char recvBuffer[COAP_MAX_PDU_SIZE] = {0};
size_t len;
int level, type, namelen;
struct sockaddr_storage srcAddr;
unsigned char *pktinfo = NULL;
+#if !defined(WSA_CMSG_DATA)
struct cmsghdr *cmp = NULL;
- struct iovec iov = { recvBuffer, sizeof (recvBuffer) };
+ struct iovec iov = { .iov_base = recvBuffer, .iov_len = sizeof (recvBuffer) };
union control
{
struct cmsghdr cmsg;
.msg_controllen = CMSG_SPACE(len) };
ssize_t recvLen = recvmsg(fd, &msg, flags);
- if (-1 == recvLen)
+ if (OC_SOCKET_ERROR == recvLen)
{
OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
return CA_STATUS_FAILED;
}
}
}
+#else // if defined(WSA_CMSG_DATA)
+ union control
+ {
+ WSACMSGHDR cmsg;
+ uint8_t data[WSA_CMSG_SPACE(sizeof (IN6_PKTINFO))];
+ } cmsg;
+ memset(&cmsg, 0, sizeof(cmsg));
+
+ if (flags & CA_IPV6)
+ {
+ namelen = sizeof (struct sockaddr_in6);
+ level = IPPROTO_IPV6;
+ type = IPV6_PKTINFO;
+ }
+ else
+ {
+ namelen = sizeof (struct sockaddr_in);
+ level = IPPROTO_IP;
+ type = IP_PKTINFO;
+ }
+ WSABUF iov = {.len = sizeof (recvBuffer), .buf = recvBuffer};
+ WSAMSG msg = {.name = &srcAddr,
+ .namelen = namelen,
+ .lpBuffers = &iov,
+ .dwBufferCount = 1,
+ .Control = {.buf = cmsg.data, .len = sizeof (cmsg)}
+ };
+
+ uint32_t recvLen = 0;
+ uint32_t ret = caglobals.ip.wsaRecvMsg(fd, &msg, &recvLen, 0,0);
+ OIC_LOG_V(DEBUG, TAG, "WSARecvMsg recvd %u bytes", recvLen);
+ if (OC_SOCKET_ERROR == ret)
+ {
+ OIC_LOG_V(ERROR, TAG, "WSARecvMsg failed %i", WSAGetLastError());
+ }
+
+ if (flags & CA_MULTICAST)
+ {
+ for (WSACMSGHDR *cmp = WSA_CMSG_FIRSTHDR(&msg); cmp != NULL;
+ cmp = WSA_CMSG_NXTHDR(&msg, cmp))
+ {
+ if (cmp->cmsg_level == level && cmp->cmsg_type == type)
+ {
+ pktinfo = WSA_CMSG_DATA(cmp);
+ }
+ }
+ }
+#endif // !defined(WSA_CMSG_DATA)
CASecureEndpoint_t sep = {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};
if (flags & CA_IPV6)
{
- sep.endpoint.interface = ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id;
- ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id = 0;
-
+ /** @todo figure out correct usage for ifindex, and sin6_scope_id.*/
if ((flags & CA_MULTICAST) && pktinfo)
{
struct in6_addr *addr = &(((struct in6_pktinfo *)pktinfo)->ipi6_addr);
}
}
- CAConvertAddrToName(&srcAddr, msg.msg_namelen, sep.endpoint.addr, &sep.endpoint.port);
+ CAConvertAddrToName(&srcAddr, namelen, sep.endpoint.addr, &sep.endpoint.port);
if (flags & CA_SECURE)
{
}
return CA_STATUS_OK;
+
}
void CAIPPullData()
OIC_LOG(DEBUG, TAG, "OUT");
}
-static int CACreateSocket(int family, uint16_t *port)
+static CASocketFd_t CACreateSocket(int family, uint16_t *port, bool isMulticast)
{
int socktype = SOCK_DGRAM;
#ifdef SOCK_CLOEXEC
socktype |= SOCK_CLOEXEC;
#endif
- int fd = socket(family, socktype, IPPROTO_UDP);
- if (-1 == fd)
+ CASocketFd_t fd = socket(family, socktype, IPPROTO_UDP);
+ if (OC_INVALID_SOCKET == fd)
{
- OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
- return -1;
+ OIC_LOG_V(ERROR, TAG, "create socket failed: %s", CAIPS_GET_ERROR);
+ return OC_INVALID_SOCKET;
}
-#ifndef SOCK_CLOEXEC
+#if !defined(SOCK_CLOEXEC) && defined(FD_CLOEXEC)
int fl = fcntl(fd, F_GETFD);
if (-1 == fl || -1 == fcntl(fd, F_SETFD, fl|FD_CLOEXEC))
{
OIC_LOG_V(ERROR, TAG, "set FD_CLOEXEC failed: %s", strerror(errno));
close(fd);
- return -1;
+ return OC_INVALID_SOCKET;
}
#endif
-
struct sockaddr_storage sa = { .ss_family = family };
socklen_t socklen;
{
int on = 1;
- if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
+ if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&on), sizeof (on)))
{
- OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", CAIPS_GET_ERROR);
}
- if (*port) // only do this for multicast ports
+ if (isMulticast && *port) // only do this for multicast ports
{
- if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
+#if defined(IPV6_RECVPKTINFO)
+ if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
+#else
+ if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, OPTVAL_T(&on), sizeof (on)))
+#endif
{
- OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s",CAIPS_GET_ERROR);
}
}
}
else
{
- if (*port) // only do this for multicast ports
+ if (isMulticast && *port) // only do this for multicast ports
{
int on = 1;
- if (-1 == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &on, sizeof (on)))
+ if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, OPTVAL_T(&on), sizeof (on)))
{
- OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", CAIPS_GET_ERROR);
}
}
socklen = sizeof (struct sockaddr_in);
}
- if (*port) // use the given port
+ if (isMulticast && *port) // use the given port
{
int on = 1;
- if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof (on)))
+ if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
{
- OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", CAIPS_GET_ERROR);
+#ifdef _WIN32
+ closesocket(fd);
+#else
close(fd);
- return -1;
+#endif
+ return OC_INVALID_SOCKET;
}
}
- if (-1 == bind(fd, (struct sockaddr *)&sa, socklen))
+ if (OC_SOCKET_ERROR == bind(fd, (struct sockaddr *)&sa, socklen))
{
- OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", CAIPS_GET_ERROR);
+#ifdef _WIN32
+ closesocket(fd);
+#else
close(fd);
- return -1;
+#endif
+ return OC_INVALID_SOCKET;
}
- if (!*port) // return the assigned port
+ if (!*port) // return the assigned port
{
- if (-1 == getsockname(fd, (struct sockaddr *)&sa, &socklen))
+ if (OC_SOCKET_ERROR == getsockname(fd, (struct sockaddr *)&sa, &socklen))
{
- OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", CAIPS_GET_ERROR);
+#ifdef _WIN32
+ closesocket(fd);
+#else
close(fd);
- return -1;
+#endif
+ return OC_INVALID_SOCKET;
}
*port = ntohs(family == AF_INET6 ?
((struct sockaddr_in6 *)&sa)->sin6_port :
#define CHECKFD(FD) \
if (FD > caglobals.ip.maxfd) \
caglobals.ip.maxfd = FD;
-#define NEWSOCKET(FAMILY, NAME) \
- caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port); \
+#define NEWSOCKET(FAMILY, NAME, MULTICAST) \
+ caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port, MULTICAST); \
+ if (caglobals.ip.NAME.fd == OC_INVALID_SOCKET) \
+ { \
+ caglobals.ip.NAME.port = 0; \
+ caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port, MULTICAST); \
+ } \
CHECKFD(caglobals.ip.NAME.fd)
static void CAInitializeNetlink()
{
+ caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
#ifdef __linux__
// create NETLINK fd for interface change notifications
struct sockaddr_nl sa = { AF_NETLINK, 0, 0, RTMGRP_LINK };
caglobals.ip.netlinkFd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_ROUTE);
- if (caglobals.ip.netlinkFd == -1)
+ if (caglobals.ip.netlinkFd == OC_INVALID_SOCKET)
{
OIC_LOG_V(ERROR, TAG, "netlink socket failed: %s", strerror(errno));
}
{
OIC_LOG_V(ERROR, TAG, "netlink bind failed: %s", strerror(errno));
close(caglobals.ip.netlinkFd);
- caglobals.ip.netlinkFd = -1;
+ caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
}
else
{
#endif
}
-static void CAInitializePipe()
+static void CAInitializeFastShutdownMechanism()
{
- caglobals.ip.selectTimeout = -1;
-#ifdef HAVE_PIPE2
- int ret = pipe2(caglobals.ip.shutdownFds, O_CLOEXEC);
+ caglobals.ip.selectTimeout = -1; // don't poll for shutdown
+ int ret = -1;
+#if defined(WSA_WAIT_EVENT_0)
+ caglobals.ip.shutdownEvent = -1;
+ caglobals.ip.shutdownEvent = WSACreateEvent();
+
+ if (caglobals.ip.shutdownEvent == WSA_INVALID_EVENT)
+ {
+ caglobals.ip.shutdownEvent = -1;
+ }
+ else
+ {
+ ret = 0;
+ }
+#elif defined(HAVE_PIPE2)
+ ret = pipe2(caglobals.ip.shutdownFds, O_CLOEXEC);
+ CHECKFD(caglobals.ip.shutdownFds[0]);
+ CHECKFD(caglobals.ip.shutdownFds[1]);
#else
- int ret = pipe(caglobals.ip.shutdownFds);
+ ret = pipe(caglobals.ip.shutdownFds);
if (-1 != ret)
{
ret = fcntl(caglobals.ip.shutdownFds[0], F_GETFD);
caglobals.ip.shutdownFds[1] = -1;
}
}
+ CHECKFD(caglobals.ip.shutdownFds[0]);
+ CHECKFD(caglobals.ip.shutdownFds[1]);
#endif
if (-1 == ret)
{
- OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "fast shutdown mechanism init failed: %s", CAIPS_GET_ERROR);
caglobals.ip.selectTimeout = SELECT_TIMEOUT; //poll needed for shutdown
}
}
{
return res;
}
-
+#if defined (_WIN32)
+ WORD wVersionRequested = MAKEWORD(2, 2);
+ WSADATA wsaData ={.wVersion = 0};
+ int err = WSAStartup(wVersionRequested, &wsaData);
+ if (err != 0)
+ {
+ OIC_LOG_V(ERROR, TAG, "WSAStartup failed: %i", err);
+ return CA_STATUS_FAILED;
+ }
+ OIC_LOG(DEBUG, TAG, "WSAStartup Succeeded");
+#endif
if (!IPv4MulticastAddress.s_addr)
{
(void)inet_pton(AF_INET, IPv4_MULTICAST, &IPv4MulticastAddress);
if (caglobals.ip.ipv6enabled)
{
- NEWSOCKET(AF_INET6, u6)
- NEWSOCKET(AF_INET6, u6s)
- NEWSOCKET(AF_INET6, m6)
- NEWSOCKET(AF_INET6, m6s)
+ NEWSOCKET(AF_INET6, u6, false)
+ NEWSOCKET(AF_INET6, u6s, false)
+ NEWSOCKET(AF_INET6, m6, true)
+ NEWSOCKET(AF_INET6, m6s, true)
OIC_LOG_V(INFO, TAG, "IPv6 unicast port: %u", caglobals.ip.u6.port);
}
if (caglobals.ip.ipv4enabled)
{
- NEWSOCKET(AF_INET, u4)
- NEWSOCKET(AF_INET, u4s)
- NEWSOCKET(AF_INET, m4)
- NEWSOCKET(AF_INET, m4s)
+ NEWSOCKET(AF_INET, u4, false)
+ NEWSOCKET(AF_INET, u4s, false)
+ NEWSOCKET(AF_INET, m4, true)
+ NEWSOCKET(AF_INET, m4s, true)
OIC_LOG_V(INFO, TAG, "IPv4 unicast port: %u", caglobals.ip.u4.port);
}
caglobals.ip.u6.port, caglobals.ip.u6s.port, caglobals.ip.u4.port,
caglobals.ip.u4s.port, caglobals.ip.m6.port, caglobals.ip.m6s.port,
caglobals.ip.m4.port, caglobals.ip.m4s.port);
- // create pipe for fast shutdown
- CAInitializePipe();
- CHECKFD(caglobals.ip.shutdownFds[0]);
- CHECKFD(caglobals.ip.shutdownFds[1]);
+#if defined (SIO_GET_EXTENSION_FUNCTION_POINTER)
+ caglobals.ip.wsaRecvMsg = NULL;
+ GUID GuidWSARecvMsg = WSAID_WSARECVMSG;
+ DWORD copied = 0;
+ err = WSAIoctl(caglobals.ip.u4.fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidWSARecvMsg, sizeof(GuidWSARecvMsg), &(caglobals.ip.wsaRecvMsg), sizeof(caglobals.ip.wsaRecvMsg), &copied, 0, 0);
+ if (0 != err)
+ {
+ OIC_LOG_V(ERROR, TAG, "WSAIoctl failed %i", WSAGetLastError());
+ return CA_STATUS_FAILED;
+ }
+#endif
+ // set up appropriate FD mechanism for fast shutdown
+ CAInitializeFastShutdownMechanism();
// create source of network interface change notifications
CAInitializeNetlink();
caglobals.ip.started = false;
caglobals.ip.terminate = true;
+#if !defined(WSA_WAIT_EVENT_0)
if (caglobals.ip.shutdownFds[1] != -1)
{
close(caglobals.ip.shutdownFds[1]);
{
// receive thread will stop in SELECT_TIMEOUT seconds.
}
+#else
+ // receive thread will stop immediately.
+ if (!WSASetEvent(caglobals.ip.shutdownEvent))
+ {
+ OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
+ }
+#endif
}
void CAWakeUpForChange()
{
+#if !defined(WSA_WAIT_EVENT_0)
if (caglobals.ip.shutdownFds[1] != -1)
{
ssize_t len = 0;
OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
}
}
+#else
+ if (!WSASetEvent(caglobals.ip.shutdownEvent))
+ {
+ OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
+ }
+#endif
}
-static void applyMulticastToInterface4(struct in_addr inaddr)
+static void applyMulticastToInterface4(uint32_t ifindex)
{
if (!caglobals.ip.ipv4enabled)
{
return;
}
+#if defined(USE_IP_MREQN)
struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
- .imr_address = inaddr,
- .imr_ifindex = 0 };
- if (setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
+ .imr_address.s_addr = htonl(INADDR_ANY),
+ .imr_ifindex = ifindex };
+#else
+ struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress,
+ .imr_interface.s_addr = htonl(ifindex) };
+#endif
+
+ int ret = setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, OPTVAL_T(&mreq), sizeof (mreq));
+ if (OC_SOCKET_ERROR == ret)
{
+#if !defined(WSAEINVAL)
if (EADDRINUSE != errno)
+#else
+ if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
+#endif
{
- OIC_LOG_V(ERROR, TAG, "IPv4 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, " IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
}
}
- if (setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
+ ret = setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, OPTVAL_T(&mreq), sizeof (mreq));
+ if (OC_SOCKET_ERROR == ret)
{
+#if !defined(WSAEINVAL)
if (EADDRINUSE != errno)
+#else
+ if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
+#endif
{
- OIC_LOG_V(ERROR, TAG, "secure IPv4 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "SECURE IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
}
}
}
-static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t interface)
+static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t ifindex)
{
- struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr, .ipv6mr_interface = interface};
-
- if (setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof (mreq)))
+ struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr,
+ .ipv6mr_interface = ifindex };
+ int ret = setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, OPTVAL_T(&mreq), sizeof (mreq));
+ if (OC_SOCKET_ERROR == ret)
{
- if (EADDRINUSE != errno)
+#if !defined(_WIN32)
+ if (EADDRINUSE != errno)
+#else
+ if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv6 Flavor)
+#endif
{
- OIC_LOG_V(ERROR, TAG, "IPv6 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "IPv6 IPV6_JOIN_GROUP failed: %s", CAIPS_GET_ERROR);
}
}
}
-static void applyMulticastToInterface6(uint32_t interface)
+static void applyMulticastToInterface6(uint32_t ifindex)
{
if (!caglobals.ip.ipv6enabled)
{
return;
}
- //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, interface);
- applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, interface);
- //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, interface);
- //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, interface);
- //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, interface);
- //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, interface);
- //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, interface);
-
- //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, interface);
- applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, interface);
- //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, interface);
- //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, interface);
- //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, interface);
- //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, interface);
- //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, interface);
+ //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, ifindex);
+ applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, ifindex);
+ //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, ifindex);
+ //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, ifindex);
+ //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, ifindex);
+ //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, ifindex);
+ //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, ifindex);
+
+ //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, ifindex);
+ applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, ifindex);
+ //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, ifindex);
+ //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, ifindex);
+ //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, ifindex);
+ //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, ifindex);
+ //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, ifindex);
}
CAResult_t CAIPStartListenServer()
u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
if (!iflist)
{
- OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "CAIPGetInterfaceInformation() failed: %s", strerror(errno));
return CA_STATUS_FAILED;
}
{
continue;
}
- if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
+ if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
{
continue;
}
if (ifitem->family == AF_INET)
{
- struct in_addr inaddr;
- inaddr.s_addr = ifitem->ipv4addr;
- applyMulticastToInterface4(inaddr);
- OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s", ifitem->name);
+ OIC_LOG_V(DEBUG, TAG, "Adding IPv4 interface %i to multicast group", ifitem->index);
+ applyMulticastToInterface4(ifitem->index);
}
if (ifitem->family == AF_INET6)
{
+ OIC_LOG_V(DEBUG, TAG, "Adding IPv6 interface %i to multicast group", ifitem->index);
applyMulticastToInterface6(ifitem->index);
- OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
}
}
{
continue;
}
-
- if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
+ if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
{
continue;
}
if (ifitem->family == AF_INET)
{
- close(caglobals.ip.m4.fd);
- close(caglobals.ip.m4s.fd);
- caglobals.ip.m4.fd = -1;
- caglobals.ip.m4s.fd = -1;
+ CLOSE_SOCKET(m4);
+ CLOSE_SOCKET(m4s);
OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s cloed", ifitem->name);
}
if (ifitem->family == AF_INET6)
{
- close(caglobals.ip.m6.fd);
- close(caglobals.ip.m6s.fd);
- caglobals.ip.m6.fd = -1;
- caglobals.ip.m6s.fd = -1;
+ CLOSE_SOCKET(m6);
+ CLOSE_SOCKET(m6s);
OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
}
}
OIC_LOG(DEBUG, TAG, "ifitem is null");
return;
}
+
if (ifitem->family == AF_INET6)
{
applyMulticastToInterface6(ifitem->index);
}
if (ifitem->family == AF_INET)
{
- struct in_addr inaddr = { .s_addr = ifitem->ipv4addr };
- applyMulticastToInterface4(inaddr);
+ applyMulticastToInterface4(ifitem->index);
}
}
}
char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
- (void)secure; // eliminates release warning
+
+ (void)cast; // eliminates release warning
+ (void)fam;
+
struct sockaddr_storage sock;
CAConvertNameToAddr(endpoint->addr, endpoint->port, &sock);
socklen_t socklen;
if (sock.ss_family == AF_INET6)
{
- struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sock;
- if (!sock6->sin6_scope_id)
- {
- sock6->sin6_scope_id = endpoint->interface;
- }
+ /** @todo figure out correct usage for ifindex, and sin6_scope_id */
socklen = sizeof(struct sockaddr_in6);
}
else
{
socklen = sizeof(struct sockaddr_in);
}
-
+#if !defined(_WIN32)
ssize_t len = sendto(fd, data, dlen, 0, (struct sockaddr *)&sock, socklen);
- if (-1 == len)
+ if (OC_SOCKET_ERROR == len)
{
// If logging is not defined/enabled.
- (void)cast;
- (void)fam;
if (g_ipErrorHandler)
{
g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
{
OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %zd bytes", secure, cast, fam, len);
}
+#else
+ int err = 0;
+ int len = 0;
+ int sent = 0;
+ do {
+ len = sendto(fd, ((char*)data) + sent, dlen - sent, 0, (struct sockaddr *)&sock, socklen);
+ if (OC_SOCKET_ERROR == len)
+ {
+ err = WSAGetLastError();
+ if ((WSAEWOULDBLOCK != err) && (WSAENOBUFS != err))
+ {
+ // If logging is not defined/enabled.
+ if (g_ipErrorHandler)
+ {
+ g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
+ }
+
+ OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %i", secure, cast, fam, err);
+ }
+ }
+ else
+ {
+ sent += len;
+ if (sent != len)
+ {
+ OIC_LOG_V(DEBUG, TAG, "%s%s %s sendTo (Partial Send) is successful: "
+ "currently sent: %ld bytes, "
+ "total sent: %ld bytes, "
+ "remaining: %ld bytes",
+ secure, cast, fam, len, sent, dlen-sent);
+ }
+ else
+ {
+ OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %ld bytes",
+ secure, cast, fam, len);
+ }
+ }
+ } while ((OC_SOCKET_ERROR == len) && ((WSAEWOULDBLOCK == err) || (WSAENOBUFS == err)) || (sent < dlen));
+#endif
}
static void sendMulticastData6(const u_arraylist_t *iflist,
{
continue;
}
- if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
+ if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
{
continue;
}
}
int index = ifitem->index;
- if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &index, sizeof (index)))
+ if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, OPTVAL_T(&index), sizeof (index)))
{
- OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", CAIPS_GET_ERROR);
return;
}
sendData(fd, endpoint, data, datalen, "multicast", "ipv6");
{
VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
+#if defined(USE_IP_MREQN)
struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
- .imr_ifindex = 0 };
+ .imr_address.s_addr = htonl(INADDR_ANY),
+ .imr_ifindex = 0};
+#else
+ struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress,
+ .imr_interface = {0}};
+#endif
+
OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
int fd = caglobals.ip.u4.fd;
{
continue;
}
- if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
+ if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
{
continue;
}
{
continue;
}
-
- struct in_addr inaddr;
- inaddr.s_addr = ifitem->ipv4addr;
- mreq.imr_address = inaddr;
- if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof (mreq)))
+#if defined(USE_IP_MREQN)
+ mreq.imr_ifindex = ifitem->index;
+#else
+ mreq.imr_interface.s_addr = htonl(ifitem->index);
+#endif
+ if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, OPTVAL_T(&mreq), sizeof (mreq)))
{
OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
- strerror(errno));
+ CAIPS_GET_ERROR);
}
sendData(fd, endpoint, data, datalen, "multicast", "ipv4");
}
endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
}
- int fd;
+ CASocketFd_t fd;
if (caglobals.ip.ipv6enabled && (endpoint->flags & CA_IPV6))
{
fd = isSecure ? caglobals.ip.u6s.fd : caglobals.ip.u6.fd;
}
eps[j].adapter = CA_ADAPTER_IP;
- eps[j].interface = 0;
+ eps[j].ifindex = 0;
if (ifitem->family == AF_INET6)
{
{
eps[j].flags = CA_IPV4;
eps[j].port = caglobals.ip.u4.port;
-
- inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
+ /** @todo eps[j].addr not populated with IPv4 address string.
+ * it was using ifitem->ipv4addr to accomplish this.
+ * Need to understand what ipv4addr means to whom*/
}
#ifdef __WITH_DTLS__
j++;
eps[j].adapter = CA_ADAPTER_IP;
- eps[j].interface = 0;
+ eps[j].ifindex = 0;
if (ifitem->family == AF_INET6)
{
return CA_STATUS_FAILED;
}
}
+ return CA_STATUS_OK;
}
static void CAIPDestroyNetworkMonitorList()
{
CAInterface_t *removedifitem = (CAInterface_t *) u_arraylist_get(
g_netInterfaceList, list_index);
- if (removedifitem && removedifitem->index == ifiindex)
+ if (removedifitem && ((int)removedifitem->index) == ifiindex)
{
if (u_arraylist_remove(g_netInterfaceList, list_index))
{
--- /dev/null
+#######################################################
+# Build IP adapter for MSYS2
+#######################################################
+
+Import('env', 'src_dir')
+import os.path
+target_os = env.get('TARGET_OS')
+env.AppendUnique(CPPPATH = [ os.path.join(src_dir, target_os) ])
+
+src_files = [ 'caipnwmonitor.c' ]
+
+Return('src_files')
--- /dev/null
+/* *****************************************************************
+*
+* Copyright 2016 Intel Corporation
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
+#include "caipinterface.h"
+
+#include <sys/types.h>
+#include <string.h>
+#include <errno.h>
+#include <winsock2.h>
+#include <iphlpapi.h>
+#include "platform_features.h"
+#include <iptypes.h>
+#include <stdbool.h>
+#include "caadapterutils.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+
+#define TAG "IP_MONITOR"
+
+/**
+ * @todo Implement network interface monitoring in case the IP changes.
+ * Not critical for win32 bring-up.
+ */
+CAResult_t CAIPStartNetworkMonitor()
+{
+ return CA_STATUS_OK;
+}
+
+/**
+ * @todo Implement network interface monitoring in case the IP changes.
+ * Not critical for win32 bring-up.
+ */
+CAResult_t CAIPStopNetworkMonitor()
+{
+ return CA_STATUS_OK;
+}
+
+/**
+ * @todo Implement network interface monitoring.
+ * Not used in win32, but caipserver currently requires this function
+ * be defined. not critical.
+ */
+int CAGetPollingInterval(int interval)
+{
+ return interval;
+}
+
+/**
+ * @todo Implement network interface monitoring.
+ * Not used in win32, but caipserver currently requires this function
+ * be defined. not critical.
+ */
+CAInterface_t *CAFindInterfaceChange()
+{
+ CAInterface_t *foundNewInterface = NULL;
+ return foundNewInterface;
+}
+
+/**
+ * @todo Implement network interface monitoring.
+ * Not critical for win32 bring-up.
+ */
+void CAIPSetNetworkMonitorCallback(CAIPConnectionStateChangeCallback callback)
+{
+ return;
+}
+
+bool IsValidAdapter(PIP_ADAPTER_ADDRESSES pAdapterAddr, int desiredIndex, uint16_t family)
+{
+ bool valid = true;
+
+ // If desiredIndex is non-zero, then only retrieve adapter corresponding to desiredIndex.
+ // If desiredIndex is zero, then retrieve all adapters.
+ if (desiredIndex && (pAdapterAddr->IfIndex != desiredIndex))
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i not interesting.", pAdapterAddr->IfIndex);
+ valid = false;
+ }
+
+ if (pAdapterAddr->IfType & IF_TYPE_SOFTWARE_LOOPBACK)
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i is loopback.", pAdapterAddr->IfIndex);
+ valid = false;
+ }
+
+ // If the adapter must support the requested family
+ if ((family == AF_INET6) && ((pAdapterAddr->Flags & IP_ADAPTER_IPV6_ENABLED) == 0))
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i does not support IPv6", pAdapterAddr->IfIndex);
+ valid = false;
+ }
+ else if ((family == AF_INET) && ((pAdapterAddr->Flags & IP_ADAPTER_IPV4_ENABLED) == 0))
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i does not support IPv4", pAdapterAddr->IfIndex);
+ valid = false;
+ }
+
+ if ((pAdapterAddr->OperStatus & IfOperStatusUp) == 0)
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i is not operational.", pAdapterAddr->IfIndex);
+ valid = false;
+ }
+ return valid;
+
+}
+
+
+bool AddCAInterface(u_arraylist_t *iflist, const char * name, uint32_t index, uint16_t family)
+{
+ bool bSucceeded = false;
+ CAInterface_t *ifitem = (CAInterface_t *)OICCalloc(1, sizeof(*ifitem));
+ if (ifitem)
+ {
+ OICStrcpy(ifitem->name, INTERFACE_NAME_MAX, name);
+ ifitem->index = index;
+ ifitem->family = family;
+ ifitem->flags |= IFF_UP;// IsValidAddress() will have filtered out non-operational addresses already.
+
+ if (u_arraylist_add(iflist, ifitem))
+ {
+ bSucceeded = true;
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "u_arraylist_add failed");
+ OICFree(ifitem);
+ }
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "Allocating memory for a CAInterface_t failed");
+ }
+ return bSucceeded;
+}
+
+bool AddInterfaces(PIP_ADAPTER_ADDRESSES pAdapterAddr, u_arraylist_t *iflist, int desiredIndex)
+{
+ bool bSucceeded = false;
+ for (PIP_ADAPTER_ADDRESSES pCurAdapterAddr = pAdapterAddr;
+ pCurAdapterAddr != NULL; pCurAdapterAddr = pCurAdapterAddr->Next)
+ {
+ OIC_LOG_V(DEBUG, TAG, "\tInterface Index: %u", pCurAdapterAddr->IfIndex);
+ OIC_LOG_V(DEBUG, TAG, "\tInterface name: %s", pCurAdapterAddr->AdapterName);
+
+ // Prefer IPv6 over IPv4.
+ if (pCurAdapterAddr->Flags & IP_ADAPTER_IPV6_ENABLED)
+ {
+ // Do not add loopback, duplicate, or non-operational adapters
+ if (IsValidAdapter(pCurAdapterAddr, desiredIndex, AF_INET6))
+ {
+ if (AddCAInterface(iflist, pCurAdapterAddr->AdapterName, pCurAdapterAddr->IfIndex, AF_INET6))
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tAdded IPv6 interface %i", pCurAdapterAddr->IfIndex);
+ bSucceeded = true;
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "\tAdding IPv6 interface %i failed", pCurAdapterAddr->IfIndex);
+ break;
+ }
+ }
+ else
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tIPv6 interface %i not valid, skipping...", pCurAdapterAddr->IfIndex);
+ }
+ }
+ else if (pCurAdapterAddr->Flags & IP_ADAPTER_IPV4_ENABLED)
+ {
+ // Do not add loopback, duplicate, or non-operational adapters
+ if (IsValidAdapter(pCurAdapterAddr, desiredIndex, AF_INET))
+ {
+ if (AddCAInterface(iflist, pCurAdapterAddr->AdapterName, pCurAdapterAddr->IfIndex, AF_INET))
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tAdded IPv4 interface %i", pCurAdapterAddr->IfIndex);
+ bSucceeded = true;
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "\tAdding IPv4 interface %i failed", pCurAdapterAddr->IfIndex);
+ break;
+ }
+ }
+ else
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tIPv6 interface %i not valid, skipping...", pCurAdapterAddr->IfIndex);
+ }
+
+ }
+ }
+ return bSucceeded;
+}
+
+PIP_ADAPTER_ADDRESSES GetAdapters()
+{
+ ULONG ulOutBufLen = sizeof(IP_ADAPTER_ADDRESSES);
+ PIP_ADAPTER_ADDRESSES pAdapterAddr = (IP_ADAPTER_ADDRESSES *) OICMalloc(ulOutBufLen);
+ if (pAdapterAddr != NULL)
+ {
+ ULONG flags = 0;
+ ULONG ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAdapterAddr, &ulOutBufLen);
+ if (ERROR_BUFFER_OVERFLOW == ret)
+ {
+ // Redo with updated length
+ OICFree(pAdapterAddr);
+ pAdapterAddr = (PIP_ADAPTER_ADDRESSES) OICMalloc(ulOutBufLen);
+ if (pAdapterAddr != NULL) {
+ ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAdapterAddr, &ulOutBufLen);
+ if (NO_ERROR != ret)
+ {
+ OIC_LOG(ERROR, TAG, "GetAdaptersAddresses() failed");
+ OICFree(pAdapterAddr);
+ pAdapterAddr = NULL;
+ }
+ else
+ {
+ // Succeeded getting adapters
+ }
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "Second time allocating memory for GetAdaptersAddresses() failed");
+ }
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "Expected GetAdaptersAddresses() to fail on first try, but it didn't.");
+ }
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "First time allocating memory for GetAdaptersAddresses() failed");
+ }
+ return pAdapterAddr;
+}
+
+u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
+{
+ u_arraylist_t *iflist = u_arraylist_create();
+ if (iflist)
+ {
+ PIP_ADAPTER_ADDRESSES pAdapterAddr = NULL;
+ pAdapterAddr = GetAdapters();
+ if (pAdapterAddr)
+ {
+ // Cycle through adapters
+ // Add valid adapters to the interface list.
+ bool ret = AddInterfaces(pAdapterAddr, iflist, desiredIndex);
+ if (false == ret)
+ {
+ OIC_LOG(ERROR, TAG, "AddInterfaces() failed");
+ u_arraylist_destroy(iflist);
+ iflist = NULL;
+ }
+
+ // Finished with Adapter List
+ OICFree(pAdapterAddr);
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "Enumerating Adapters failed");
+ u_arraylist_destroy(iflist);
+ iflist = NULL;
+ }
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "Failed to create iflist");
+ }
+ return iflist;
+}
VERIFY_NON_NULL(g_jvm, TAG, "g_jvm");\r
\r
bool isAttached = false;\r
- JNIEnv* env;\r
+ JNIEnv* env = NULL;\r
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);\r
if (JNI_OK != res)\r
{\r
\r
OIC_LOG(INFO, TAG, "CANFCStartServer : IN");\r
\r
- JNIEnv* env;\r
+ JNIEnv* env = NULL;\r
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);\r
if (JNI_OK != res)\r
{\r
\r
OIC_LOG(INFO, TAG, "CANfcSendDataImpl moved env outside");\r
bool isAttached = false;\r
- JNIEnv* env;\r
+ JNIEnv* env = NULL;\r
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);\r
if (JNI_OK != res)\r
{\r
}
}
-static void CATCPConnectionHandler(const char *addr, uint16_t port, bool isConnected)
+static void CATCPConnectionHandler(const CAEndpoint_t *endpoint, bool isConnected)
{
- CAEndpoint_t endpoint = { .adapter = CA_ADAPTER_TCP,
- .port = port };
- OICStrcpy(endpoint.addr, sizeof(endpoint.addr), addr);
-
// Pass the changed connection status to RI Layer for keepalive.
if (g_connKeepAliveCallback)
{
- g_connKeepAliveCallback(&endpoint, isConnected);
+ g_connKeepAliveCallback(endpoint, isConnected);
}
// Pass the changed connection status to CAUtil.
if (g_connectionChangeCallback)
{
- g_connectionChangeCallback(&endpoint, isConnected);
+ g_connectionChangeCallback(endpoint, isConnected);
}
}
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;
{
OIC_LOG(DEBUG, TAG, "IN");
+ // Specific the port number received from application.
+ caglobals.tcp.ipv4.port = caglobals.ports.tcp.u4;
+ caglobals.tcp.ipv6.port = caglobals.ports.tcp.u6;
+
#ifndef SINGLE_THREAD
if (CA_STATUS_OK != CATCPInitializeQueueHandles())
{
static int CACreateAcceptSocket(int family, CASocket_t *sock);
static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
static void CAFindReadyMessage();
-static void CASelectReturned(fd_set *readFds, int ret);
+static void CASelectReturned(fd_set *readFds);
static void CAReceiveMessage(int fd);
static void CAReceiveHandler(void *data);
static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo);
return;
}
- CASelectReturned(&readFds, ret);
+ CASelectReturned(&readFds);
}
-static void CASelectReturned(fd_set *readFds, int ret)
+static void CASelectReturned(fd_set *readFds)
{
VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
if (!sock6->sin6_scope_id)
{
- sock6->sin6_scope_id = svritem->sep.endpoint.interface;
+ sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
}
socklen = sizeof(struct sockaddr_in6);
}
}
}
+#define NEWSOCKET(FAMILY, NAME) \
+ caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
+ if (caglobals.tcp.NAME.fd == -1) \
+ { \
+ caglobals.tcp.NAME.port = 0; \
+ caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
+ } \
+ CHECKFD(caglobals.tcp.NAME.fd);
+
CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
{
if (caglobals.tcp.started)
if (caglobals.server)
{
- caglobals.tcp.ipv4.fd = CACreateAcceptSocket(AF_INET, &caglobals.tcp.ipv4);
- CHECKFD(caglobals.tcp.ipv4.fd);
- caglobals.tcp.ipv6.fd = CACreateAcceptSocket(AF_INET6, &caglobals.tcp.ipv6);
- CHECKFD(caglobals.tcp.ipv6.fd);
-
+ NEWSOCKET(AF_INET, ipv4);
+ NEWSOCKET(AF_INET6, ipv6);
OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
return NULL;
}
memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
+ svritem->sep.endpoint.adapter = endpoint->adapter;
svritem->sep.endpoint.port = endpoint->port;
svritem->sep.endpoint.flags = endpoint->flags;
- svritem->sep.endpoint.interface = endpoint->interface;
+ svritem->sep.endpoint.ifindex = endpoint->ifindex;
// #2. create the socket and connect to TCP server
int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
// pass the connection information to CA Common Layer.
if (g_connectionCallback)
{
- g_connectionCallback(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, true);
+ g_connectionCallback(&(svritem->sep.endpoint), true);
}
return svritem;
// pass the connection information to CA Common Layer.
if (g_connectionCallback)
{
- g_connectionCallback(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, false);
+ g_connectionCallback(&(svritem->sep.endpoint), false);
}
OICFree(svritem);
# Build flags
######################################################################
catest_env.PrependUnique(CPPPATH = [
- '../../ocsocket/include',
'../../logger/include',
'../../stack/include',
'../../extlibs/cjson',
catest_env.Replace(LINKFLAGS = tmplist)
catest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
-catest_env.AppendUnique(LIBS = ['pthread'])
catest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
catest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs'])
-catest_env.PrependUnique(LIBS = ['m',
- 'octbstack',
+catest_env.PrependUnique(LIBS = ['octbstack',
'connectivity_abstraction',
'coap',
'gtest',
target_os = env.get('TARGET_OS')
-if target_os not in ['arduino', 'darwin', 'ios']:
+if target_os not in ['arduino', 'darwin', 'ios', 'msys_nt', 'windows']:
catest_env.AppendUnique(LIBS=['rt'])
if env.get('SECURED') == '1':
- catest_env.AppendUnique(LIBS = ['tinydtls'])
+ catest_env.AppendUnique(LIBS = ['tinydtls'])
+ catest_env.AppendUnique(LIBS = ['timer'])
+
+if env.get('WITH_RD') == '1':
+ catest_env.PrependUnique(LIBS = ['resource_directory'])
if env.get('LOGGING'):
catest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+if target_os in ['msys_nt', 'windows']:
+ catest_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE'])
+ catest_env.AppendUnique(LIBS = ['ws2_32',
+ 'advapi32',
+ 'iphlpapi'])
+else:
+ catest_env.PrependUnique(LIBS = ['m', 'pthread'])
+
######################################################################
# Source files and Targets
######################################################################
env.AppendTarget('test')
if env.get('TEST') == '1':
- if target_os == 'linux':
+ if target_os in ['linux', 'windows']:
+ catest_env.AppendENVPath('PATH', env.get('BUILD_DIR'))
from tools.scons.RunTest import *
run_test(catest_env,
'resource_csdk_connectivity_test.memcheck',
*
******************************************************************/
+#include "platform_features.h"
#include "gtest/gtest.h"
#include "cainterface.h"
#include "cautilinterface.h"
}
#endif //__WITH_DTLS__
-int main(int argc, char **argv)
-{
- testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-
// CAInitialize TC
// check return value
TEST(InitializeTest, TC_01_Positive_01)
class CABlockTransferTests : public testing::Test {
protected:
- virtual void SetUp() {
+ virtual void SetUp()
+ {
CAInitialize();
}
#include <camutex.h>
#include <cathreadpool.h>
+#ifdef HAVE_TIME_H
#include <time.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#include "platform_features.h"
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+
+#define HNS_PER_US 10
//#define DEBUG_VERBOSE 1
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
currentTime = ts.tv_sec * USECS_PER_SEC + ts.tv_nsec / 1000;
+#elif defined(_WIN32)
+ FILETIME time;
+ ULARGE_INTEGER microseconds;
+
+ GetSystemTimeAsFileTime(&time);
+
+ // Time is in hundreds of nanoseconds, so we must convert to uS
+ microseconds.LowPart = time.dwLowDateTime;
+ microseconds.HighPart = time.dwHighDateTime;
+ microseconds.QuadPart /= HNS_PER_US;
+
+ currentTime = microseconds.QuadPart;
#else
struct timeval tv;
gettimeofday(&tv, NULL);
DBG_printf("Thread_%d: completed.\n", pData->id);
}
+#ifdef _WIN32
+/** @todo: Enable. Need to solve nanosleep issue */
+TEST(ConditionTests, DISABLED_TC_02_SIGNAL)
+#else
TEST(ConditionTests, TC_02_SIGNAL)
+#endif
{
const int MAX_WAIT_MS = 2000;
ca_thread_pool_t mythreadpool;
ca_thread_pool_free(mythreadpool);
}
-TEST(CondTests, TC_04_TIMECHECK)
+#ifdef _WIN32
+/** @todo: Enable. Need to solve nanosleep issue */
+TEST(ConditionTests, DISABLED_TC_04_TIMECHECK)
+#else
+TEST(ConditionTests, TC_04_TIMECHECK)
+#endif
{
uint64_t begin = getAbsTime();
double secondsDiff = (end - beg) / (double) USECS_PER_SEC;
+#ifdef _WIN32
+ // Windows does not guarantee that the thread will resume execution from a
+ // yield within any given time frame. We will assume that the threads
+ // should have resumed within one second of the requested timeout value.
+ EXPECT_NEAR(TARGET_WAIT, secondsDiff, 1.00);
+#else
EXPECT_NEAR(TARGET_WAIT, secondsDiff, 0.05);
+#endif
ca_mutex_unlock(sharedMutex);
#include "gtest/gtest.h"
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
/**
pthread_key_delete(key);
}
}
+#else
+void workaroundHook()
+{
+ return;
+};
+#endif
TEST(BaseTest, WorldIsSane)
* @return ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
*/
CAResult_t CAManagerLEClientTerminate(JNIEnv *env);
+
+/**
+ * set BLE scan interval time and working count.
+ * @param[in] intervalTime interval time(Seconds).
+ * @param[in] workingCount working count for selected interval time.
+ */
+void CAManagerLESetScanInterval(jint intervalTime, jint workingCount);
+
#endif
#ifdef __cplusplus
static void CABTPaitingCreateJNIInterfaceObject(jobject context)
{
- JNIEnv* env;
+ JNIEnv* env = NULL;
OIC_LOG(INFO, TAG, "OICEDRCreateJNIInterfaceObject");
if ((*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
VERIFY_NON_NULL(address, TAG, "address");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
VERIFY_NON_NULL(address, TAG, "address");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
return res;
}
+void CAManagerLESetScanInterval(jint interval, jint count)
+{
+ OIC_LOG(DEBUG, TAG, "CAManagerLESetScanInterval");
+ CALERestartScanWithInterval(interval, count);
+}
+
JNIEXPORT void JNICALL
Java_org_iotivity_ca_CaLeClientInterface_caManagerAdapterStateChangedCallback(
JNIEnv *env, jobject obj, jint state)
static void CAManagerConnectionMonitorHandler(const CAEndpoint_t *info, bool isConnected)
{
- if (!info || !info->addr)
+ if (!info || !info->addr[0])
{
OIC_LOG(ERROR, TAG, "remoteAddress is NULL");
return;
#endif
}
+CAResult_t CASetPortNumberToAssign(CATransportAdapter_t adapter,
+ CATransportFlags_t flag, uint16_t port)
+{
+ uint16_t *targetPort = 0;
+
+ if (CA_ADAPTER_IP & adapter)
+ {
+ if (CA_SECURE & flag)
+ {
+ if (CA_IPV6 & flag)
+ {
+ targetPort = &caglobals.ports.udp.u6s;
+ }
+ else if (CA_IPV4 & flag)
+ {
+ targetPort = &caglobals.ports.udp.u4s;
+ }
+ }
+ else
+ {
+ if (CA_IPV6 & flag)
+ {
+ targetPort = &caglobals.ports.udp.u6;
+ }
+ else if (CA_IPV4 & flag)
+ {
+ targetPort = &caglobals.ports.udp.u4;
+ }
+ }
+ }
+#ifdef TCP_ADAPTER
+ if (CA_ADAPTER_TCP & adapter)
+ {
+ if (CA_IPV6 & flag)
+ {
+ targetPort = &caglobals.ports.tcp.u6;
+ }
+ else if (CA_IPV4 & flag)
+ {
+ targetPort = &caglobals.ports.tcp.u4;
+ }
+ }
+#endif
+
+ if (targetPort)
+ {
+ *targetPort = port;
+ return CA_STATUS_OK;
+ }
+
+ return CA_NOT_SUPPORTED;
+}
+
+uint16_t CAGetAssignedPortNumber(CATransportAdapter_t adapter, CATransportFlags_t flag)
+{
+ OIC_LOG(DEBUG, TAG, "CAGetAssignedPortNumber");
+
+ if (CA_ADAPTER_IP & adapter)
+ {
+ if (CA_SECURE & flag)
+ {
+ if (CA_IPV6 & flag)
+ {
+ return caglobals.ip.u6s.port;
+ }
+ else if (CA_IPV4 & flag)
+ {
+ return caglobals.ip.u4s.port;
+ }
+ }
+ else
+ {
+ if (CA_IPV6 & flag)
+ {
+ return caglobals.ip.u6.port;
+ }
+ else if (CA_IPV4 & flag)
+ {
+ return caglobals.ip.u4.port;
+ }
+ }
+ }
+#ifdef TCP_ADAPTER
+ if (CA_ADAPTER_TCP & adapter)
+ {
+ if (CA_IPV6 & flag)
+ {
+ return caglobals.tcp.ipv6.port;
+ }
+ else if (CA_IPV4 & flag)
+ {
+ return caglobals.tcp.ipv4.port;
+ }
+ }
+#endif
+ return 0;
+}
+
#ifdef __ANDROID__
/**
* initialize client connection manager
(void)listener;
#endif
}
+
+CAResult_t CAUtilSetLEScanInterval(jint intervalTime, jint workingCount)
+{
+ OIC_LOG(DEBUG, TAG, "CAUtilSetLEScanInterval");
+#ifdef LE_ADAPTER
+ CAManagerLESetScanInterval(intervalTime, workingCount);
+ return CA_STATUS_OK;
+#else
+ OIC_LOG(DEBUG, TAG, "it is not supported");
+ return CA_NOT_SUPPORTED;
+#endif
+}
#endif
Import('env')
import os
-env.AppendUnique(CPPPATH = [os.path.join(Dir('.').abspath, './include')])
+env.AppendUnique(CPPPATH = [os.path.join(Dir('.').abspath, 'include'),
+ '../../c_common'
+ ])
+
if env.get('TARGET_OS') in ['arduino']:
env.AppendUnique(CPPPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/c_common/oic_string/include')])
if env.get('TARGET_OS') == 'tizen':
env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
else:
- env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/csdk/logger/')])
+ env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk', 'logger')])
env.PrependUnique(LIBS = ['logger'])
#ifndef LOGGER_H_
#define LOGGER_H_
-#define IOTIVITY_VERSION "1.1.0"
+#define IOTIVITY_VERSION "1.1.1"
#include <stdint.h>
#include <stdio.h>
FATAL = DLOG_ERROR
} LogLevel;
#else
+
+/** @todo temporary work-around until better names with prefixes are used for the enum values. */
+#ifdef ERROR
+#undef ERROR
+#endif
+
typedef enum {
DEBUG = 0,
INFO,
#define OCLog(level,tag,mes) LOG_(LOG_ID_MAIN, (level), (tag), mes)
#define OCLogv(level,tag,fmt,args...) LOG_(LOG_ID_MAIN, (level),tag,fmt,##args)
-#elif defined(ANDROID) || defined(__linux__) || defined(__APPLE__)
+#elif !defined(ARDUINO)
/**
* Configure logger to use a context that defines a custom logger function
*
#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)\
OCLogBuffer((level), (tag), (buffer), (bufferSize))
-#else // These macros are defined for Linux, Android, and Arduino
+#else // These macros are defined for Linux, Android, Win32, and Arduino
#define OIC_LOG_INIT() OCLogInit()
#define OIC_LOG_CONFIG(ctx) OCLogConfig((ctx))
#define OIC_LOG_SHUTDOWN() OCLogShutdown()
#define OIC_LOG(level, tag, logStr) OCLog((level), (tag), (logStr))
-// Define variable argument log function for Linux and Android
+// Define variable argument log function for Linux, Android, and Win32
#define OIC_LOG_V(level, tag, ...) OCLogv((level), (tag), __VA_ARGS__)
#endif //ARDUINO
#define _POSIX_C_SOURCE 200809L
#endif
-// Platform check can be extended to check and/or define more, or could be
-// moved into a config.h
-#if !defined(__ARDUINO__) && !defined(ARDUINO)
-#define HAVE_UNISTD_H 1
-#endif
-
// Pull in _POSIX_TIMERS feature test macro to check for
// clock_gettime() support.
#ifdef HAVE_UNISTD_H
#include <unistd.h>
-
-// if we have unistd.h, we're a Unix system
+#endif
#include <time.h>
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include "logger.h"
#include "string.h"
#include "logger_types.h"
+#include "platform_features.h"
#ifndef __TIZEN__
static oc_log_ctx_t *logCtx = 0;
#endif
+
+#if defined(_MSC_VER)
+#define LINE_BUFFER_SIZE (16 * 2) + 16 + 1 // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
+#else
+static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1; // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
+#endif //defined(_MSC_VER)
+
#ifdef __ANDROID__
-#elif defined __linux__ || defined __APPLE__
+#elif defined __linux__ || defined __APPLE__ || defined _WIN32
static oc_log_level LEVEL_XTABLE[] = {OC_LOG_DEBUG, OC_LOG_INFO,
OC_LOG_WARNING, OC_LOG_ERROR, OC_LOG_FATAL};
#endif
-// Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
-static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1;
-
// Convert LogLevel to platform-specific severity level. Store in PROGMEM on Arduino
#ifdef __ANDROID__
#ifdef ADB_SHELL
static android_LogPriority LEVEL[] =
{ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL};
#endif
-#elif defined (__linux__) || defined (__APPLE__)
- static const char *LEVEL[] __attribute__ ((unused)) =
- {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+#elif defined(__linux__) || defined(__APPLE__) || defined(__msys_nt__)
+ static const char * LEVEL[] __attribute__ ((unused)) = {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+#elif defined(_MSC_VER)
+ static const char * LEVEL[] = {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
#elif defined ARDUINO
#include <stdarg.h>
#include "Arduino.h"
#else
#define GET_PROGMEM_BUFFER(buffer, addr) { buffer[0] = '\0';}
#endif
-#endif // __ANDROID__
+#else // !defined(__ANDROID__) && !defined(ARDUINO)
+ static const char *LEVEL[] __attribute__ ((unused)) =
+ {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+#endif
#ifndef ARDUINO
void OCLogShutdown()
{
-#if defined(__linux__) || defined(__APPLE__)
+#if defined(__linux__) || defined(__APPLE__) || defined(_WIN32)
if (logCtx && logCtx->destroy)
{
logCtx->destroy(logCtx);
if (!format || !tag) {
return;
}
- char buffer[MAX_LOG_V_BUFFER_SIZE] = {};
+ char buffer[MAX_LOG_V_BUFFER_SIZE] = {0};
va_list args;
va_start(args, format);
vsnprintf(buffer, sizeof buffer - 1, format, args);
__android_log_write(LEVEL[level], tag, logStr);
#endif
- #elif defined __linux__ || defined __APPLE__
+ #else
if (logCtx && logCtx->write_level)
{
logCtx->write_level(logCtx, LEVEL_XTABLE[level], logStr);
sec = when.tv_sec % 60;
ms = when.tv_nsec / 1000000;
}
+ #elif defined(_WIN32)
+ SYSTEMTIME systemTime = {0};
+ GetLocalTime(&systemTime);
+ min = (int)systemTime.wMinute;
+ sec = (int)systemTime.wSecond;
+ ms = (int)systemTime.wMilliseconds;
#else
struct timeval now;
if (!gettimeofday(&now, NULL))
OIC_LOG_V(DEBUG, RM_TAG, "createoption dlen %u slen [%u]", dLen, sLen);
unsigned int totalLength = 0;
- void *tempData = NULL;
+ uint8_t *tempData = NULL;
+
if (0 == dLen && 0 == sLen)
{
OIC_LOG(DEBUG, RM_TAG, "Source and destination is not present");
##
Import('env')
+import os
lib_env = env.Clone()
SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env')
'../security/provisioning/include'
])
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows']:
libocsrm_env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
- libocsrm_env.AppendUnique(CFLAGS = ['-std=c99'])
- libocsrm_env.AppendUnique(CPPDEFINES = ['HAVE_STRINGS_H'])
-
-if target_os not in ['windows', 'winrt']:
- libocsrm_env.AppendUnique(CFLAGS = ['-Wall'])
+ libocsrm_env.AppendUnique(CFLAGS = ['-std=c99', '-Wall'])
libocsrm_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-libocsrm_env.AppendUnique(LIBS = ['coap', 'm'])
+libocsrm_env.AppendUnique(LIBS = ['coap'])
if target_os == 'arduino':
libocsrm_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO'])
-else:
+elif target_os not in ['windows', 'msys_nt']:
libocsrm_env.AppendUnique(CFLAGS = ['-fPIC'])
+ libocsrm_env.AppendUnique(LIBS = ['m'])
+
+if target_os in ['windows', 'msys_nt']:
+ libocsrm_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'oc_logger')])
if target_os in ['darwin', 'ios']:
libocsrm_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
libocsrm_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
libocsrm_env.AppendUnique(LIBS = ['coap'])
-if not env.get('RELEASE'):
+if env.get('LOGGING'):
libocsrm_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
if env.get('DTLS_WITH_X509') == '1':
# Source files and Targets
######################################################################
OCSRM_SRC = 'src/'
+libocsrm_src = [
+ OCSRM_SRC + 'secureresourcemanager.c',
+ OCSRM_SRC + 'resourcemanager.c',
+ OCSRM_SRC + 'aclresource.c',
+ OCSRM_SRC + 'verresource.c',
+ OCSRM_SRC + 'amaclresource.c',
+ OCSRM_SRC + 'amsmgr.c',
+ OCSRM_SRC + 'pstatresource.c',
+ OCSRM_SRC + 'doxmresource.c',
+ OCSRM_SRC + 'credresource.c',
+ OCSRM_SRC + 'svcresource.c',
+ OCSRM_SRC + 'pconfresource.c',
+ OCSRM_SRC + 'dpairingresource.c',
+ OCSRM_SRC + 'policyengine.c',
+ OCSRM_SRC + 'psinterface.c',
+ OCSRM_SRC + 'srmresourcestrings.c',
+ OCSRM_SRC + 'srmutility.c',
+ OCSRM_SRC + 'iotvticalendar.c',
+ OCSRM_SRC + 'base64.c',
+ OCSRM_SRC + 'directpairing.c'
+ ]
+
if env.get('SECURED') == '1':
- libocsrm_src = [
- OCSRM_SRC + 'secureresourcemanager.c',
- OCSRM_SRC + 'resourcemanager.c',
- OCSRM_SRC + 'aclresource.c',
- OCSRM_SRC + 'amaclresource.c',
- OCSRM_SRC + 'amsmgr.c',
- OCSRM_SRC + 'pstatresource.c',
- OCSRM_SRC + 'doxmresource.c',
- OCSRM_SRC + 'credresource.c',
- OCSRM_SRC + 'svcresource.c',
- OCSRM_SRC + 'pconfresource.c',
- OCSRM_SRC + 'dpairingresource.c',
- OCSRM_SRC + 'verresource.c',
- OCSRM_SRC + 'policyengine.c',
- OCSRM_SRC + 'psinterface.c',
- OCSRM_SRC + 'srmresourcestrings.c',
- OCSRM_SRC + 'srmutility.c',
- OCSRM_SRC + 'iotvticalendar.c',
- OCSRM_SRC + 'oxmpincommon.c',
- OCSRM_SRC + 'base64.c',
- #pbkdf2.c is required to PIN based OxM only.
- #But we did not use a separate build options to prevent the build command becomes complicated.
- OCSRM_SRC + 'pbkdf2.c',
- OCSRM_SRC + 'directpairing.c'
- ]
-else:
- libocsrm_src = [
- OCSRM_SRC + 'secureresourcemanager.c',
- OCSRM_SRC + 'resourcemanager.c',
- OCSRM_SRC + 'aclresource.c',
- OCSRM_SRC + 'amaclresource.c',
- OCSRM_SRC + 'amsmgr.c',
- OCSRM_SRC + 'pstatresource.c',
- OCSRM_SRC + 'doxmresource.c',
- OCSRM_SRC + 'credresource.c',
- OCSRM_SRC + 'svcresource.c',
- OCSRM_SRC + 'pconfresource.c',
- OCSRM_SRC + 'dpairingresource.c',
- OCSRM_SRC + 'policyengine.c',
- OCSRM_SRC + 'verresource.c',
- OCSRM_SRC + 'psinterface.c',
- OCSRM_SRC + 'srmresourcestrings.c',
- OCSRM_SRC + 'srmutility.c',
- OCSRM_SRC + 'iotvticalendar.c',
- OCSRM_SRC + 'base64.c',
- OCSRM_SRC + 'directpairing.c'
- ]
+ libocsrm_src = libocsrm_src + [OCSRM_SRC + 'oxmpincommon.c', OCSRM_SRC + 'pbkdf2.c']
+
+if target_os in ['windows', 'msys_nt']:
+ libocsrm_src = libocsrm_src + [OCSRM_SRC + 'strptime.c']
if env.get('DTLS_WITH_X509') == '1' and env.get('SECURED') == '1':
crl_src = [OCSRM_SRC + 'crlresource.c']
libocsrm_src = libocsrm_src + crl_src
+libocsrm_conf = Configure(libocsrm_env)
+if libocsrm_conf.CheckFunc('strptime'):
+ libocsrm_conf.env.AppendUnique(CPPDEFINES = ['HAVE_STRPTIME'])
+libocsrm_env = libocsrm_conf.Finish()
-libocsrm = libocsrm_env.StaticLibrary('libocsrm', libocsrm_src)
+libocsrm = libocsrm_env.StaticLibrary('ocsrm', libocsrm_src)
-libocsrm_env.InstallTarget(libocsrm, 'libocsrm')
+libocsrm_env.InstallTarget(libocsrm, 'ocsrm')
-if target_os in ['linux', 'android', 'tizen'] and env.get('SECURED') == '1':
+if target_os in ['linux', 'android', 'tizen', 'msys_nt', 'windows'] and env.get('SECURED') == '1':
SConscript('provisioning/SConscript')
if target_os in ['linux'] and env.get('SECURED') == '1':
*
* @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.
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.
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
* @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.
*
* @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
/**
* 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.
/**\r
* Start direct-pairing processes.\r
*\r
+ * @param[in] ctx user context passed back with resultCallback.\r
* @param[in] peer target device to establish direct-pairing.\r
* @param[in] pmSel selected pairing method.\r
* @param[in] pinNumber secret value for dtls connection.\r
*\r
* @return OC_STACK_OK on success otherwise error.\r
*/\r
-OCStackResult DPDirectPairing(OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, char *pinNumber,\r
- OCDirectPairingResultCB resultCallback);\r
+OCStackResult DPDirectPairing(void *ctx, OCDirectPairingDev_t* peer, OicSecPrm_t pmSel,\r
+ char *pinNumber, OCDirectPairingResultCB resultCallback);\r
\r
/**\r
* This function returns discovered devices list in direct-pairing discovery\r
#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;
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;
//Security Version
extern const char * DEFAULT_SEC_VERSION;
+#ifdef __cplusplus
+}
+#endif
+
#endif //IOTVT_SRM_RSRC_STRINGS_H
#include "byte_array.h"
#endif /* __WITH_X509__ */
+#include "platform_features.h"
+
#ifdef __cplusplus
extern "C" {
#endif
/**
* Extract Reason Code from Access Response.
*/
-static inline SRMAccessResponseReasonCode_t GetReasonCode(
+INLINE_API SRMAccessResponseReasonCode_t GetReasonCode(
SRMAccessResponse_t response)
{
SRMAccessResponseReasonCode_t reason =
/**
* Returns 'true' iff request should be passed on to RI layer.
*/
-static inline bool IsAccessGranted(SRMAccessResponse_t response)
+INLINE_API bool IsAccessGranted(SRMAccessResponse_t response)
{
if(ACCESS_GRANTED == (response & ACCESS_GRANTED))
{
}
}
+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;
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;
{
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;
};
/**
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
};
/**
{
// <Attribute ID>:<Read/Write>:<Multiple/Single>:<Mandatory?>:<Type>
//TODO fill in from OIC Security Spec
+#if defined(_MSC_VER)
+ uint8_t unused; // VS doesn't like empty structs
+#endif
};
/**
'../../../c_common/ocrandom/include',
'../../logger/include',
'../../../oc_logger/include',
- '../../ocmalloc/include',
+ '../../../c_common/oic_malloc/include',
'include',
'include/internal',
'include/oxm',
'../../resource/csdk/security/include',
'../../../../extlibs/cjson/',
- '../../../../../extlibs/tinydtls/',
+ '../../../../extlibs/tinydtls/',
'../../connectivity/inc',
'../../connectivity/external/inc',
'../../connectivity/common/inc',
if target_os != 'tizen':
provisioning_env.AppendUnique(CPPPATH = ['../../../../extlibs/sqlite3'])
-provisioning_env.AppendUnique(CFLAGS = ['-D__WITH_DTLS__'])
-provisioning_env.AppendUnique(CFLAGS = ['-std=c99'])
-if target_os not in ['windows', 'winrt']:
- provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread', '-D__WITH_DTLS__'])
+provisioning_env.AppendUnique(CPPDEFINES= ['__WITH_DTLS__'])
+if target_os not in ['windows']:
+ provisioning_env.AppendUnique(CFLAGS = ['-std=c99'])
+if target_os not in ['windows', 'msys_nt']:
+ provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
# Note: 'pthread' is in libc for android. On other platform, if use
# new gcc(>4.9?) it isn't required, otherwise, it's required
if target_os != 'android':
provisioning_env.AppendUnique(LIBS = ['-lpthread', '-ldl'])
-
provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
provisioning_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap'])
if env.get('DTLS_WITH_X509') == '1':
provisioning_env.AppendUnique(LIBS = ['CKManager', 'asn1'])
-if target_os != 'android':
+if target_os not in ['msys_nt', 'windows', 'android']:
provisioning_env.ParseConfig('pkg-config --libs glib-2.0')
+if target_os in ['windows', 'msys_nt']:
+ provisioning_env.AppendUnique(LIBS = ['ws2_32', 'advapi32', 'iphlpapi', 'timer'])
+
if target_os == 'tizen':
provisioning_env.ParseConfig('pkg-config --cflags --libs sqlite3')
if target_os != 'tizen':
provisioning_src = provisioning_src + [root_dir+'/extlibs/sqlite3/sqlite3.c' ]
-provisioningserver = provisioning_env.SharedLibrary('ocpmapi', provisioning_src)
+if target_os == 'windows':
+ # TODO: Add OC_EXPORT annotations and enable generation of Windows DLL
+ provisioningserver = provisioning_env.StaticLibrary('ocpmapi', provisioning_src)
+else:
+ provisioningserver = provisioning_env.SharedLibrary('ocpmapi', provisioning_src)
-provisioning_env.InstallTarget(provisioningserver, 'libocpmapi')
-provisioning_env.UserInstallTargetLib(provisioningserver, 'libocpmapi')
+provisioning_env.InstallTarget(provisioningserver, 'ocpmapi')
+provisioning_env.UserInstallTargetLib(provisioningserver, 'ocpmapi')
if env.get('DTLS_WITH_X509') == '1':
SConscript('ck_manager/SConscript')
-if target_os in ['linux']:
+if target_os in ['linux', 'msys_nt', 'windows']:
SConscript('sample/SConscript')
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
+ },{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
+ },{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/presence",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
- "href": "/oic/sec/crl",\r
+ "href": "/oic/sec/cred",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.cred"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
- "href": "/oic/sec/cred",\r
+ "href": "/oic/sec/crl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.crl"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 6\r
"owned": false,\r
"deviceuuid": "646F6F72-4465-7669-6365-555549443030",\r
"rowneruuid": "646F6F72-4465-7669-6365-555549443030",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
}\r
}
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
+ },{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
+ },{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/presence",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
- "href": "/oic/sec/crl",\r
+ "href": "/oic/sec/cred",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.cred"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
- "href": "/oic/sec/cred",\r
+ "href": "/oic/sec/crl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.crl"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 6\r
"owned": false,\r
"deviceuuid": "6C696768-7444-6576-6963-655555494430",\r
"rowneruuid": "6C696768-7444-6576-6963-655555494430",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
}\r
}
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
+ },{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
+ },{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/ad",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } ,\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
"deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
"devowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
"rowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
}\r
}
\ No newline at end of file
#define MAX_URI_LENGTH (64)
#define MAX_PERMISSION_LENGTH (5)
+#define MAX_ACL_LENGTH 100
#define CREATE (1)
#define READ (2)
#define UPDATE (4)
*/
static void deleteACL(OicSecAcl_t *acl)
{
- if (acl)
+ if (acl && MAX_ACL_LENGTH > acl->resourcesLen)
{
/* Clean Resources */
for (size_t i = 0; i < (acl)->resourcesLen; i++)
//Set Resource.
printf("Num. of Resource : \n");
ret = scanf("%zu", &acl->resourcesLen);
- if(-1 == ret)
+ if(-1 == ret || MAX_ACL_LENGTH < acl->resourcesLen)
{
printf("Error while input\n");
return -1;
######################################################################
# Source files and Targets
######################################################################
-unittest = pki_test_env.Program('unittest', ['pki_test.cpp'])
+unittest = pki_test_env.Program('unittest', ['pki_test.cpp',
+ 'ckm_info_test.cpp',
+ 'crl_generator_test.cpp',
+ 'csr_generator_test.cpp'])
Alias("test", [unittest])
unittest_src_dir = src_dir + '/resource/csdk/security/provisioning/ck_manager/unittest/test_data/'
-unittest_build_dir = env.get('BUILD_DIR') +'/resource/csdk/security/provisioning/ck_manager/unittest'
+unittest_build_dir = env.get('BUILD_DIR') +'resource/csdk/security/provisioning/ck_manager/unittest'
+
+pki_test_env.AppendUnique(CPPDEFINES = ['SECURITY_BUILD_UNITTEST_DIR='+unittest_build_dir])
pki_test_env.Alias("install",env.Install( unittest_build_dir, [ unittest_src_dir + '01.der',
unittest_src_dir + 'cacert.der',
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')
--- /dev/null
+/******************************************************************
+ *
+ * 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());
+}
--- /dev/null
+/******************************************************************
+ *
+ * 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);
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * 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);
+ }
+}
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)
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;
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);
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);
//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))
//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};
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);
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
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);
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)
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
+ },{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
+ },{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/ad",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } ,\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/cred",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.cred"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 7\r
"deviceuuid": "61646d69-6e44-6576-6963-655555494430",\r
"devowneruuid": "61646d69-6e44-6576-6963-655555494430",\r
"rowneruuid": "61646d69-6e44-6576-6963-655555494430",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
}\r
}
\ No newline at end of file
#include "ocstack.h"
#include "securevirtualresourcetypes.h"
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
/**
* Function to generate credentials according to the type.
*
*/
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.
OCProvisionResultCB resultCallback);\r
\r
/**\r
+ * this function requests CRED information to resource.\r
+ *\r
+ * @param[in] ctx Application context would be returned in result callback.\r
+ * @param[in] selectedDeviceInfo Selected target device.\r
+ * @param[in] resultCallback callback provided by API user, callback will be called when provisioning\r
+ request recieves a response from resource server.\r
+ * @return OC_STACK_OK in case of success and other value otherwise.\r
+ */\r
+OCStackResult OCGetCredResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,\r
+ OCProvisionResultCB resultCallback);\r
+\r
+/**\r
+ * this function requests ACL information to resource.\r
+ *\r
+ * @param[in] ctx Application context would be returned in result callback.\r
+ * @param[in] selectedDeviceInfo Selected target device.\r
+ * @param[in] resultCallback callback provided by API user, callback will be called when provisioning\r
+ request recieves a response from resource server.\r
+ * @return OC_STACK_OK in case of success and other value otherwise.\r
+ */\r
+OCStackResult OCGetACLResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,\r
+ OCProvisionResultCB resultCallback);\r
+\r
+/**\r
* this function sends Direct-Pairing Configuration to a device.\r
*\r
* @param[in] ctx Application context would be returned in result callback.\r
/**
* 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
#
Import('env')
+import os.path
provisioning_env = env.Clone()
'../../../connectivity/api'
])
-provisioning_env.AppendUnique(CFLAGS = ['-D__WITH_DTLS__','-std=c99'])
-provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread', '-fpermissive'])
+target_os = env.get('TARGET_OS')
provisioning_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
-provisioning_env.AppendUnique(LIBS = ['-lpthread','-ldl'])
-provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-provisioning_env.PrependUnique(LIBS = ['ocpmapi','oc', 'oc_logger', 'ocsrm','m', 'octbstack', 'connectivity_abstraction', 'coap'])
+provisioning_env.AppendUnique(CPPDEFINES = ['__WITH_DTLS__'])
+
+if target_os not in ['windows']:
+ provisioning_env.AppendUnique(CFLAGS = ['-std=c99'])
+ provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread', '-fpermissive'])
+ provisioning_env.AppendUnique(LIBS = ['-lpthread'])
+
+if target_os not in ['msys_nt', 'windows']:
+ provisioning_env.AppendUnique(LIBS = ['-ldl', 'm'])
+ provisioning_env.ParseConfig('pkg-config --libs glib-2.0');
+ provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+else:
+ provisioning_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk')])
+ provisioning_env.AppendUnique(LIBS = ['ws2_32', 'iphlpapi', 'advapi32', 'timer'])
+
+provisioning_env.PrependUnique(LIBS = ['ocpmapi','oc', 'oc_logger', 'ocsrm', 'octbstack', 'connectivity_abstraction', 'coap'])
if env.get('SECURED') == '1':
provisioning_env.AppendUnique(LIBS = ['tinydtls'])
if env.get('DTLS_WITH_X509') == '1':
provisioning_env.AppendUnique(LIBS = ['CKManager'])
provisioning_env.AppendUnique(LIBS = ['asn1'])
-provisioning_env.ParseConfig('pkg-config --libs glib-2.0');
provisioning_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
+ },{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
+ },{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
+ }\r
+ ],\r
+ "permission": 2\r
+ },\r
+ {\r
+ "subjectuuid": "*",\r
+ "resources": [\r
{\r
- "href": "/oic/ad",\r
+ "href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
- "href": "/oic/sec/amacl",\r
+ "href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
"subjectuuid": "*",\r
"resources": [\r
{\r
- "href": "/oic/sec/doxm",\r
+ "href": "/oic/sec/pconf",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pconf"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
- "href": "/oic/sec/pstat",\r
+ "href": "/oic/sec/dpairing",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } \r
+ "rt": ["oic.r.dpairing"],\r
+ "if": ["oic.if.baseline"]\r
+ }\r
],\r
"permission": 2\r
}\r
]\r
},\r
"rowneruuid" : "61646D69-6E44-6576-6963-655575696430"\r
- }, \r
+ },\r
"pstat": {\r
"isop": true,\r
"cm": 0,\r
"sct": 1,\r
"owned": true,\r
"deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
- "dpc": false,\r
+ "x.com.samsung.dpc": false,\r
"devowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
"rowneruuid": "61646D69-6E44-6576-6963-655575696430"\r
}\r
{
"href": "/oic/res",
"rel": "",
- "rt": "",
- "if": ""
- },
- {
+ "rt": ["oic.wk.res"],
+ "if": ["oic.if.ll"]
+ },{
"href": "/oic/d",
"rel": "",
- "rt": "",
- "if": ""
- },
- {
+ "rt": ["oic.wk.d"],
+ "if": ["oic.if.baseline", "oic.if.r"]
+ },{
"href": "/oic/p",
"rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/res/d",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/res/types/d",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/presence",
- "rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
}
],
"permission": 2
{
"href": "/oic/sec/doxm",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.doxm"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/pstat",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.pstat"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/acl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.acl"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/cred",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.cred"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 6
{
"href": "/oic/sec/pconf",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.pconf"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/dpairing",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.dpairing"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 6
{
"href": "/oic/sec/ver",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.ver"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 2
"deviceuuid": "",
"devowneruuid": "",
"rowneruuid": "",
- "dpc": true
+ "x.com.samsung.dpc": true
}
}
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
},{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/presence",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/cred",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.cred"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 6\r
{\r
"href": "/oic/sec/pconf",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pconf"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/dpairing",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.dpairing"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 6\r
{\r
"href": "/oic/sec/ver",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.ver"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
"deviceuuid": "6A757374-776F-726B-4465-765575696430",\r
"devowneruuid": "",\r
"rowneruuid": "6A757374-776F-726B-4465-765575696430",\r
- "dpc": true\r
+ "x.com.samsung.dpc": true\r
}\r
-}
\ No newline at end of file
+}\r
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
+ },{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
+ },{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/presence",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/cred",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.cred"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 6\r
{\r
"href": "/oic/sec/pconf",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pconf"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/dpairing",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.dpairing"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 6\r
{\r
"href": "/oic/sec/ver",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.ver"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
"deviceuuid": "72616E64-5069-6E44-6576-557569643030",\r
"devowneruuid": "",\r
"rowneruuid": "72616E64-5069-6E44-6576-557569643030",\r
- "dpc": true\r
+ "x.com.samsung.dpc": true\r
}\r
}\r
#include <stdio.h>
#include <string.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#include "platform_features.h"
+#include "utlist.h"
#include "logger.h"
#include "oic_malloc.h"
#include "oic_string.h"
#define _34_CHECK_LINK_STATUS_ 34
#define _40_UNLINK_PAIR_DEVS_ 40
#define _50_REMOVE_SELEC_DEV_ 50
+#define _60_GET_CRED_ 60
+#define _61_GET_ACL_ 61
#define _99_EXIT_PRVN_CLT_ 99
#define ACL_RESRC_MAX_NUM 16
+#define ACL_RESRC_ARRAY_SIZE 3 //This value is used only for sample (not OCF spec)
#define ACL_RESRC_MAX_LEN 128
#define ACL_PEMISN_CNT 5
#define DISCOVERY_TIMEOUT 10 // 10 sec
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)
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
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;
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( ; ; )
// enter actually each 'accessed' |resources| name
printf(" Enter Each Accessed Resource Name (each under 128 char)\n");
// '128' is ACL_RESRC_MAX_LEN
- acl->resourcesLen = (unsigned) num;
- acl->resources = (char**) OICCalloc(acl->resourcesLen, sizeof(char*));
- if(!acl->resources)
- {
- OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
- goto CRACL_ERROR;
- }
+
char rsrc_in[ACL_RESRC_MAX_LEN+1] = {0}; // '1' for null termination
- for(int i=0; acl->resourcesLen>(unsigned)i; ++i)
+ for(int i = 0; num > i; ++i)
{
+ OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+ if(!rsrc)
+ {
+ OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+ goto CRACL_ERROR;
+ }
+
printf(" Enter Accessed Resource[%d] Name: ", i+1);
for(int ret=0; 1!=ret; )
{
// '0x20<=code' is character region
}
size_t len = strlen(rsrc_in)+1; // '1' for null termination
- char* rsrc = (char*) OICCalloc(len, sizeof(char));
+ rsrc->href = (char*) OICCalloc(len, sizeof(char));
if(!rsrc)
{
OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
goto CRACL_ERROR;
}
- OICStrcpy(rsrc, len, rsrc_in);
- acl->resources[i] = rsrc; // after here, |rsrc| points nothing
+ OICStrcpy(rsrc->href, len, rsrc_in);
+
+ int arrLen = 0;
+ while(1)
+ {
+ printf(" Enter Number of resource type for [%s]: ", rsrc_in);
+ for(int ret=0; 1!=ret; )
+ {
+ ret = scanf("%d", &arrLen);
+ for( ; 0x20<=getchar(); ); // for removing overflow garbages
+ // '0x20<=code' is character region
+ }
+ if(0 < arrLen && ACL_RESRC_ARRAY_SIZE >= arrLen)
+ {
+ break;
+ }
+ printf(" Entered Wrong Number. Please Enter under %d Again\n", ACL_RESRC_ARRAY_SIZE);
+ }
+
+ rsrc->typeLen = arrLen;
+ rsrc->types = (char**)OICCalloc(arrLen, sizeof(char*));
+ if(!rsrc->types)
+ {
+ OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+ goto CRACL_ERROR;
+ }
+
+ for(int i = 0; i < arrLen; i++)
+ {
+ printf(" Enter ResourceType[%d] Name: ", i+1);
+ for(int ret=0; 1!=ret; )
+ {
+ ret = scanf("%128s", rsrc_in); // '128' is ACL_RESRC_MAX_LEN
+ for( ; 0x20<=getchar(); ); // for removing overflow garbages
+ // '0x20<=code' is character region
+ }
+ rsrc->types[i] = OICStrdup(rsrc_in);
+ if(!rsrc->types[i])
+ {
+ OIC_LOG(ERROR, TAG, "createAcl: OICStrdup error return");
+ goto CRACL_ERROR;
+ }
+ }
+
+ while(1)
+ {
+ printf(" Enter Number of interface name for [%s]: ", rsrc_in);
+ for(int ret=0; 1!=ret; )
+ {
+ ret = scanf("%d", &arrLen);
+ for( ; 0x20<=getchar(); ); // for removing overflow garbages
+ // '0x20<=code' is character region
+ }
+ if(0 < arrLen && ACL_RESRC_ARRAY_SIZE >= arrLen)
+ {
+ break;
+ }
+ printf(" Entered Wrong Number. Please Enter under %d Again\n", ACL_RESRC_ARRAY_SIZE);
+ }
+
+ rsrc->interfaceLen = arrLen;
+ rsrc->interfaces = (char**)OICCalloc(arrLen, sizeof(char*));
+ if(!rsrc->interfaces)
+ {
+ OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+ goto CRACL_ERROR;
+ }
+
+ for(int i = 0; i < arrLen; i++)
+ {
+ printf(" Enter ResourceType[%d] Name: ", i+1);
+ for(int ret=0; 1!=ret; )
+ {
+ ret = scanf("%128s", rsrc_in); // '128' is ACL_RESRC_MAX_LEN
+ for( ; 0x20<=getchar(); ); // for removing overflow garbages
+ // '0x20<=code' is character region
+ }
+ rsrc->interfaces[i] = OICStrdup(rsrc_in);
+ if(!rsrc->interfaces[i])
+ {
+ OIC_LOG(ERROR, TAG, "createAcl: OICStrdup error return");
+ goto CRACL_ERROR;
+ }
+ }
+
+ LL_APPEND(ace->resources, rsrc);
}
// enter |permission| for this access
}
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;
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;
}
printf("** [E] REMOVE THE SELECTED DEVICE\n");
printf("** 50. Remove the Selected Device\n\n");
+ printf("** [F] GET SECURITY RESOURCE FOR DEBUGGING ONLY\n");
+ printf("** 60. Get the Credential resources of the Selected Device\n");
+ printf("** 61. Get the ACL resources of the Selected Device\n\n");
+
printf("** [F] EXIT PROVISIONING CLIENT\n");
printf("** 99. Exit Provisionong Client\n\n");
OIC_LOG(ERROR, TAG, "_50_REMOVE_SELEC_DEV_: error");
}
break;
+ case _60_GET_CRED_:
+ if(getCred())
+ {
+ OIC_LOG(ERROR, TAG, "_60_GET_CRED_: error");
+ }
+ break;
+ case _61_GET_ACL_:
+ if(getAcl())
+ {
+ OIC_LOG(ERROR, TAG, "_61_GET_ACL_: error");
+ }
+ break;
case _99_EXIT_PRVN_CLT_:
goto PMCLT_ERROR;
default:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
-#include <signal.h>
+#endif
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#include <signal.h>
#include "ocstack.h"
-#include "logger.h"
#include "ocpayload.h"
+#include "pinoxmcommon.h"
+
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+/** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
+#ifdef ERROR
+#undef ERROR
+#endif //ERROR
+#endif //HAVE_WINDOWS_H
+#include "platform_features.h"
+#include "logger.h"
+
#define TAG "SAMPLE_JUSTWORKS"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
-#include <signal.h>
+#endif
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#include <signal.h>
#include "ocstack.h"
-#include "logger.h"
#include "ocpayload.h"
#include "pinoxmcommon.h"
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+/** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
+#ifdef ERROR
+#undef ERROR
+#endif //ERROR
+#endif //HAVE_WINDOWS_H
+#include "platform_features.h"
+#include "logger.h"
+
#define TAG "SAMPLE_RANDOMPIN"
int gQuitFlag = 0;
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;
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;
}
}
/**
+ * 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.
#define _POSIX_C_SOURCE 200809L
#endif
+#ifdef HAVE_TIME_H
#include <time.h>
+#endif
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
#include <stdbool.h>
#include <string.h>
* @param[in] otmCtx Context value of ownership transfer.
* @return OC_STACK_OK on success
*/
-static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx);
+static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx);
/**
* Function to send request to resource to get its pstat resource information.
* @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
* @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
* @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.
* @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.
* @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.
* @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)
{
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");
&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)
{
//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.");
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;
}
}
}
- //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;
}
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");
{
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");
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)
{
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);
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.");
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");
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)
{
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);
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;
}
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");
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)
{
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)
{
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)
{
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);
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)
{
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);
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;
}
}
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");
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)
{
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);
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)
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)
{
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);
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)
OIC_LOG(ERROR, TAG, "OCStack resource error");
}
- OIC_LOG(INFO, TAG, "OUT PutNormalOperationStatus");
+ OIC_LOG(INFO, TAG, "OUT PostNormalOperationStatus");
return ret;
}
#define _POSIX_C_SOURCE 200112L
#endif
+#if HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_STRING_H
#include <string.h>
-#include <time.h>
-#include <sys/time.h>
+#endif
#include "ocstack.h"
#include "oic_malloc.h"
#include "oic_string.h"
+#include "oic_time.h"
#include "logger.h"
#include "cJSON.h"
#include "utlist.h"
*/
OCStackResult PMTimeout(unsigned short waittime, bool waitForStackResponse)
{
- struct timespec startTime = {.tv_sec=0, .tv_nsec=0};
- struct timespec currTime = {.tv_sec=0, .tv_nsec=0};
-
OCStackResult res = OC_STACK_OK;
-#ifdef _POSIX_MONOTONIC_CLOCK
- int clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);
-#else
- int clock_res = clock_gettime(CLOCK_REALTIME, &startTime);
-#endif
- if (0 != clock_res)
- {
- return OC_STACK_ERROR;
- }
+
+ uint64_t startTime = OICGetCurrentTime(TIME_IN_MS);
while (OC_STACK_OK == res)
{
-#ifdef _POSIX_MONOTONIC_CLOCK
- clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
-#else
- clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
-#endif
- if (0 != clock_res)
- {
- return OC_STACK_TIMEOUT;
- }
- long elapsed = (currTime.tv_sec - startTime.tv_sec);
+ uint64_t currTime = OICGetCurrentTime(TIME_IN_MS);
+
+ long elapsed = (long)((currTime - startTime) / MS_PER_SEC);
if (elapsed > waittime)
{
return OC_STACK_OK;
}
bool PMGenerateQuery(bool isSecure,
- const char* address, const uint16_t port,
- const OCConnectivityType connType,
+ const char* address, uint16_t port,
+ OCConnectivityType connType,
char* buffer, size_t bufferSize, const char* uri)
{
if(!address || !buffer || !uri)
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;
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,
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");
{
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");
{
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;
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");
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");
#include <stdio.h>
#include <string.h>
#include <stdint.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
#include "ocprovisioningmanager.h"
#include "secureresourceprovider.h"
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.
*/
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);
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))
{
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,
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);
OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDevice");
return res;
}
+
+/**
+ * Internal Function to store results in result array during GetCredResourceCB.
+ */
+static void registerResultForGetCredResourceCB(GetSecData_t *GetSecData,
+ OCStackResult stackresult)
+{
+ OIC_LOG_V(INFO, TAG, "Inside registerResultForGetCredResourceCB "
+ "GetSecData->numOfResults is %d\n", GetSecData->numOfResults);
+ memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
+ GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
+ GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
+ ++(GetSecData->numOfResults);
+}
+
+/**
+ * Callback handler of SRPGetCredResource.
+ *
+ * @param[in] ctx ctx value passed to callback from calling function.
+ * @param[in] UNUSED handle to an invocation
+ * @param[in] clientResponse Response from queries to remote servers.
+ * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
+ * and OC_STACK_KEEP_TRANSACTION to keep it.
+ */
+static OCStackApplicationResult SRPGetCredResourceCB(void *ctx, OCDoHandle UNUSED,
+ OCClientResponse *clientResponse)
+{
+ OIC_LOG_V(INFO, TAG, "Inside SRPGetCredResourceCB.");
+ (void)UNUSED;
+ VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
+ GetSecData_t *GetSecData = (GetSecData_t*)ctx;
+ OCProvisionResultCB resultCallback = GetSecData->resultCallback;
+
+ if (clientResponse)
+ {
+ if(OC_STACK_OK == clientResponse->result)
+ {
+ uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
+ size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
+
+ OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
+
+ registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
+ ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
+ GetSecData->resArr,
+ false);
+ OICFree(GetSecData->resArr);
+ OICFree(GetSecData);
+
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+ }
+ registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
+ ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
+ GetSecData->resArr,
+ false);
+ OIC_LOG_V(ERROR, TAG, "SRPGetCredResourceCB received Null clientResponse");
+ OICFree(GetSecData->resArr);
+ OICFree(GetSecData);
+
+ return OC_STACK_DELETE_TRANSACTION;
+}
+
+
+OCStackResult SRPGetCredResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
+ OCProvisionResultCB resultCallback)
+{
+ VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR, OC_STACK_INVALID_PARAM);
+ VERIFY_NON_NULL(TAG, resultCallback, ERROR, OC_STACK_INVALID_CALLBACK);
+
+ char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
+ if(!PMGenerateQuery(true,
+ selectedDeviceInfo->endpoint.addr,
+ selectedDeviceInfo->securePort,
+ selectedDeviceInfo->connType,
+ query, sizeof(query), OIC_RSRC_CRED_URI))
+ {
+ OIC_LOG(ERROR, TAG, "SRPGetCredResource : Failed to generate query");
+ return OC_STACK_ERROR;
+ }
+ OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
+
+ OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
+ cbData.cb = &SRPGetCredResourceCB;
+ GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
+ if (NULL == GetSecData)
+ {
+ OIC_LOG(ERROR, TAG, "Unable to allocate memory");
+ return OC_STACK_NO_MEMORY;
+ }
+ GetSecData->deviceInfo = selectedDeviceInfo;
+ GetSecData->resultCallback = resultCallback;
+ GetSecData->numOfResults=0;
+ GetSecData->ctx = ctx;
+
+ int noOfRiCalls = 1;
+ GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
+ if (NULL == GetSecData->resArr)
+ {
+ OICFree(GetSecData);
+ OIC_LOG(ERROR, TAG, "Unable to allocate memory");
+ return OC_STACK_NO_MEMORY;
+ }
+ cbData.context = (void *)GetSecData;
+ cbData.cd = NULL;
+ OCMethod method = OC_REST_GET;
+ OCDoHandle handle = NULL;
+ OIC_LOG(DEBUG, TAG, "Sending Get Cred to resource server");
+ OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
+ selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
+ if (OC_STACK_OK != ret)
+ {
+ OIC_LOG(ERROR, TAG, "OCStack resource error");
+ OICFree(GetSecData->resArr);
+ OICFree(GetSecData);
+ }
+ VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
+ OIC_LOG(DEBUG, TAG, "OUT SRPGetCredResource");
+
+ return OC_STACK_OK;
+}
+
+/**
+ * Internal Function to store results in result array during GetACLResourceCB.
+ */
+static void registerResultForGetACLResourceCB(GetSecData_t *GetSecData,
+ OCStackResult stackresult)
+{
+ OIC_LOG_V(INFO, TAG, "Inside registerResultForGetACLResourceCB "
+ "GetSecData->numOfResults is %d\n", GetSecData->numOfResults);
+ memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
+ GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
+ GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
+ ++(GetSecData->numOfResults);
+}
+
+/**
+ * Callback handler of SRPGetACLResource.
+ *
+ * @param[in] ctx ctx value passed to callback from calling function.
+ * @param[in] UNUSED handle to an invocation
+ * @param[in] clientResponse Response from queries to remote servers.
+ * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
+ * and OC_STACK_KEEP_TRANSACTION to keep it.
+ */
+static OCStackApplicationResult SRPGetACLResourceCB(void *ctx, OCDoHandle UNUSED,
+ OCClientResponse *clientResponse)
+{
+ OIC_LOG_V(INFO, TAG, "Inside SRPGetACLResourceCB.");
+ (void)UNUSED;
+ VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
+ GetSecData_t *GetSecData = (GetSecData_t*)ctx;
+ OCProvisionResultCB resultCallback = GetSecData->resultCallback;
+
+ if (clientResponse)
+ {
+ if(OC_STACK_OK == clientResponse->result)
+ {
+ uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
+ size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
+
+ OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
+
+ registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
+ ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
+ GetSecData->resArr,
+ false);
+ OICFree(GetSecData->resArr);
+ OICFree(GetSecData);
+
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+ }
+ registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
+ ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
+ GetSecData->resArr,
+ false);
+ OIC_LOG_V(ERROR, TAG, "SRPGetACLResourceCB received Null clientResponse");
+ OICFree(GetSecData->resArr);
+ OICFree(GetSecData);
+
+ return OC_STACK_DELETE_TRANSACTION;
+}
+
+
+OCStackResult SRPGetACLResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
+ OCProvisionResultCB resultCallback)
+{
+ VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR, OC_STACK_INVALID_PARAM);
+ VERIFY_NON_NULL(TAG, resultCallback, ERROR, OC_STACK_INVALID_CALLBACK);
+
+ char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
+ if(!PMGenerateQuery(true,
+ selectedDeviceInfo->endpoint.addr,
+ selectedDeviceInfo->securePort,
+ selectedDeviceInfo->connType,
+ query, sizeof(query), OIC_RSRC_ACL_URI))
+ {
+ OIC_LOG(ERROR, TAG, "SRPGetACLResource : Failed to generate query");
+ return OC_STACK_ERROR;
+ }
+ OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
+
+ OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
+ cbData.cb = &SRPGetACLResourceCB;
+ GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
+ if (NULL == GetSecData)
+ {
+ OIC_LOG(ERROR, TAG, "Unable to allocate memory");
+ return OC_STACK_NO_MEMORY;
+ }
+ GetSecData->deviceInfo = selectedDeviceInfo;
+ GetSecData->resultCallback = resultCallback;
+ GetSecData->numOfResults=0;
+ GetSecData->ctx = ctx;
+
+ int noOfRiCalls = 1;
+ GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
+ if (NULL == GetSecData->resArr)
+ {
+ OICFree(GetSecData);
+ OIC_LOG(ERROR, TAG, "Unable to allocate memory");
+ return OC_STACK_NO_MEMORY;
+ }
+ cbData.context = (void *)GetSecData;
+ cbData.cd = NULL;
+ OCMethod method = OC_REST_GET;
+ OCDoHandle handle = NULL;
+ OIC_LOG(DEBUG, TAG, "Sending Get ACL to resource server");
+ OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
+ selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
+ if (OC_STACK_OK != ret)
+ {
+ OIC_LOG(ERROR, TAG, "OCStack resource error");
+ OICFree(GetSecData->resArr);
+ OICFree(GetSecData);
+ }
+ VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
+ OIC_LOG(DEBUG, TAG, "OUT SRPGetACLResource");
+
+ return OC_STACK_OK;
+}
sptest_env = env.Clone()
src_dir = sptest_env.get('SRC_DIR')
+target_os = env.get('TARGET_OS')
######################################################################
# Build flags
######################################################################
sptest_env.PrependUnique(CPPPATH = [
- '../../../connectivity/inc',
- '../../../connectivity/api',
+ '../include',
'../../include',
- '../../../../../extlibs/tinydtls',
'../include/internal',
- '../include/oxm',
+ '../../../stack/include',
+ '../../../ocrandom/include',
'../../../logger/include',
'../../../stack/include',
+ '../../../security/include',
+ '../../../security/include/internal',
+ '../../../security/provisioning/include/internal',
'../../../../oc_logger/include',
- '../../../../../extlibs/gtest/gtest-1.7.0/include',
- '../include',
- '../include/internal'
+ '../include/oxm',
+ '../../../../../extlibs/tinydtls',
+ '../../../../../extlibs/cjson',
+ '../../../../../extlibs/base64',
+ '../../../connectivity/inc',
+ '../../../connectivity/common/inc',
+ '../../../connectivity/lib/libcoap-4.1.1',
+ '../../../connectivity/api',
+ '../../../../../extlibs/tinydtls',
+ '../../../../../extlibs/gtest/gtest-1.7.0/include'
])
sptest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
sptest_env.AppendUnique(LIBS = ['-lpthread','-ldl'])
'gtest_main'])
if env.get('SECURED') == '1':
+ sptest_env.AppendUnique(LIBS = ['timer'])
sptest_env.AppendUnique(LIBS = ['tinydtls'])
if env.get('DTLS_WITH_X509') == '1':
sptest_env.AppendUnique(LIBS = ['CKManager'])
if not env.get('RELEASE'):
sptest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+if target_os in ['msys_nt', 'windows']:
+ sptest_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE'])
+ sptest_env.AppendUnique(LIBS = ['ws2_32',
+ 'advapi32',
+ 'iphlpapi'])
+
######################################################################
# Source files and Targets
######################################################################
-unittest = sptest_env.Program('unittest', ['pmutilitytest.cpp', 'otmunittest.cpp',
- 'secureresourceprovider.cpp',
- 'provisioningdatabasemanager.cpp',
- 'ocprovisioningmanager.cpp' ])
+unittest_src = ['pmutilitytest.cpp',
+ 'secureresourceprovider.cpp',
+ 'provisioningdatabasemanager.cpp',
+ 'ocprovisioningmanager.cpp',
+ 'credentialgeneratortest.cpp',
+ ]
+
+if target_os not in ['windows']:
+ unittest_src += [ 'otmunittest.cpp' ]
+
+unittest = sptest_env.Program('unittest', unittest_src)
+
+if target_os not in ['windows']:
+ sample_server1 = sptest_env.Program('sample_server1', ['sampleserver1.cpp'])
+ sample_server2 = sptest_env.Program('sample_server2', ['sampleserver2.cpp'])
+ Alias("test", [sample_server1, sample_server2])
Alias("test", [unittest])
env.AppendTarget('test')
if env.get('TEST') == '1':
- target_os = env.get('TARGET_OS')
- if target_os == 'linux':
+ if target_os in ['linux', 'windows']:
out_dir = env.get('BUILD_DIR')
result_dir = env.get('BUILD_DIR') + '/test_out/'
if not os.path.isdir(result_dir):
os.makedirs(result_dir)
sptest_env.AppendENVPath('GTEST_OUTPUT', ['xml:'+ result_dir])
sptest_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir])
+ sptest_env.AppendENVPath('PATH', env.get('BUILD_DIR'))
sptest_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
ut = sptest_env.Command ('ut', None, out_dir + '/resource/csdk/security/provisioning/unittest/unittest')
AlwaysBuild ('ut')
--- /dev/null
+/* *****************************************************************
+ *
+ * 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__
+
(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;
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));
+}
* 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;
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);
+}
+
--- /dev/null
+/******************************************************************
+*
+* 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;
+}
--- /dev/null
+/******************************************************************
+*
+* 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;
+}
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#ifdef WITH_ARDUINO
+#ifdef HAVE_STRING_H
#include <string.h>
-#else
+#elif HAVE_STRINGS_H
#include <strings.h>
#endif
#include <stdlib.h>
+#include "utlist.h"
#include "ocstack.h"
+#include "octypes.h"
#include "ocserverrequest.h"
#include "oic_malloc.h"
#include "oic_string.h"
#define TAG "SRM-ACL"
#define NUMBER_OF_SEC_PROV_RSCS 4
#define NUMBER_OF_DEFAULT_SEC_RSCS 2
+#define STRING_UUID_SIZE (UUID_LENGTH * 2 + 5)
static const uint8_t ACL_MAP_SIZE = 2;
static const uint8_t ACL_ACLIST_MAP_SIZE = 1;
static OCResourceHandle gAclHandle = NULL;
/**
+ * This function frees OicSecRsrc_t object's fields and object itself.
+ */
+static void FreeRsrc(OicSecRsrc_t *rsrc)
+{
+ //Clean each member of resource
+ OICFree(rsrc->href);
+ OICFree(rsrc->rel);
+ //Clean "rt"
+ if(0 < rsrc->typeLen && rsrc->types)
+ {
+ for(size_t i = 0; i < rsrc->typeLen; i++)
+ {
+ OICFree(rsrc->types[i]);
+ }
+ OICFree(rsrc->types);
+ rsrc->types = NULL;
+ }
+ //Clean "if"
+ if(0 < rsrc->interfaceLen && rsrc->interfaces)
+ {
+ for(size_t i = 0; i < rsrc->interfaceLen; i++)
+ {
+ OICFree(rsrc->interfaces[i]);
+ }
+ OICFree(rsrc->interfaces);
+ rsrc->interfaces = NULL;
+ }
+ OICFree(rsrc);
+ rsrc = NULL;
+}
+
+/**
* This function frees OicSecAcl_t object's fields and object itself.
*/
-static void FreeACE(OicSecAcl_t *ace)
+static void FreeACE(OicSecAce_t *ace)
{
- size_t i;
if (NULL == ace)
{
OIC_LOG(ERROR, TAG, "Invalid Parameter");
return;
}
- // Clean Resources
- for (i = 0; i < ace->resourcesLen; i++)
+ //Clean Resources
+ OicSecRsrc_t* rsrc = NULL;
+ OicSecRsrc_t* tmpRsrc = NULL;
+ LL_FOREACH_SAFE(ace->resources, rsrc, tmpRsrc)
{
- OICFree(ace->resources[i]);
+ LL_DELETE(ace->resources, rsrc);
+ FreeRsrc(rsrc);
}
- OICFree(ace->resources);
- //Clean Period
- if (ace->periods)
+ //Clean Validities
+ OicSecValidity_t *validity = NULL;
+ OicSecValidity_t *tmpValidity = NULL;
+ LL_FOREACH_SAFE(ace->validities, validity, tmpValidity)
{
- for (i = 0; i < ace->prdRecrLen; i++)
- {
- OICFree(ace->periods[i]);
- }
- OICFree(ace->periods);
- }
+ LL_DELETE(ace->validities, validity);
- //Clean Recurrence
- if (ace->recurrences)
- {
- for (i = 0; i < ace->prdRecrLen; i++)
+ //Clean period
+ OICFree(validity->period);
+
+ //Clean recurrence
+ for(size_t i = 0; i < validity->recurrenceLen; i++)
{
- OICFree(ace->recurrences[i]);
+ OICFree(validity->recurrences[i]);
}
- OICFree(ace->recurrences);
+ OICFree(validity->recurrences);
+ OICFree(validity);
+ validity = NULL;
}
- // Clean ACL node itself
+ //Clean ACE
OICFree(ace);
+ ace = NULL;
}
void DeleteACLList(OicSecAcl_t* acl)
{
if (acl)
{
- OicSecAcl_t *aclTmp1 = NULL;
- OicSecAcl_t *aclTmp2 = NULL;
- LL_FOREACH_SAFE(acl, aclTmp1, aclTmp2)
+ OicSecAce_t *ace = NULL;
+ OicSecAce_t *tmpAce = NULL;
+ LL_FOREACH_SAFE(acl->aces, ace, tmpAce)
{
- LL_DELETE(acl, aclTmp1);
- FreeACE(aclTmp1);
+ LL_DELETE(acl->aces, ace);
+ FreeACE(ace);
+ }
+ acl->aces = NULL;
+ OICFree(acl);
+ }
+}
+
+OicSecAce_t* DuplicateACE(const OicSecAce_t* ace)
+{
+ OicSecAce_t* newAce = NULL;
+ size_t allocateSize = 0;
+
+ if(ace)
+ {
+ newAce = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+ VERIFY_NON_NULL(TAG, newAce, ERROR);
+
+ //Subject uuid
+ memcpy(&newAce->subjectuuid, &ace->subjectuuid, sizeof(OicUuid_t));
+
+ OicSecRsrc_t* rsrc = NULL;
+ LL_FOREACH(ace->resources, rsrc)
+ {
+ OicSecRsrc_t* newRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+ VERIFY_NON_NULL(TAG, newRsrc, ERROR);
+ LL_APPEND(newAce->resources, newRsrc);
+
+ //href is mandatory
+ VERIFY_NON_NULL(TAG, rsrc->href, ERROR);
+ allocateSize = strlen(rsrc->href) + 1;
+ newRsrc->href = (char*)OICMalloc(sizeof(char) * allocateSize);
+ VERIFY_NON_NULL(TAG, newRsrc->href, ERROR);
+ OICStrcpy(newRsrc->href, allocateSize, rsrc->href);
+
+ if(rsrc->rel)
+ {
+ allocateSize = strlen(rsrc->rel) + 1;
+ newRsrc->rel = (char*)OICMalloc(sizeof(char) * allocateSize);
+ VERIFY_NON_NULL(TAG, newRsrc->rel, ERROR);
+ OICStrcpy(newRsrc->rel, allocateSize, rsrc->rel);
+ }
+
+ if(rsrc->types && 0 < rsrc->typeLen)
+ {
+ newRsrc->typeLen = rsrc->typeLen;
+ newRsrc->types = (char**)OICCalloc(rsrc->typeLen, sizeof(char*));
+ VERIFY_NON_NULL(TAG, (newRsrc->types), ERROR);
+ for(size_t i = 0; i < rsrc->typeLen; i++)
+ {
+ newRsrc->types[i] = OICStrdup(rsrc->types[i]);
+ VERIFY_NON_NULL(TAG, (newRsrc->types[i]), ERROR);
+ }
+ }
+
+ if(rsrc->interfaces && 0 < rsrc->interfaceLen)
+ {
+ newRsrc->interfaceLen = rsrc->interfaceLen;
+ newRsrc->interfaces = (char**)OICCalloc(rsrc->interfaceLen, sizeof(char*));
+ VERIFY_NON_NULL(TAG, (newRsrc->interfaces), ERROR);
+ for(size_t i = 0; i < rsrc->interfaceLen; i++)
+ {
+ newRsrc->interfaces[i] = OICStrdup(rsrc->interfaces[i]);
+ VERIFY_NON_NULL(TAG, (newRsrc->interfaces[i]), ERROR);
+ }
+ }
+ }
+
+ //Permission
+ newAce->permission = ace->permission;
+
+ //Validity
+ if(ace->validities)
+ {
+ OicSecValidity_t* validity = NULL;
+ LL_FOREACH(ace->validities, validity)
+ {
+ OicSecValidity_t* newValidity = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+ VERIFY_NON_NULL(TAG, newValidity, ERROR);
+ LL_APPEND(newAce->validities, newValidity);
+
+ if(validity->period)
+ {
+ allocateSize = strlen(validity->period) + 1;
+ newValidity->period = (char*)OICMalloc(sizeof(char) * allocateSize);
+ VERIFY_NON_NULL(TAG, newValidity->period, ERROR);
+ OICStrcpy(newValidity->period, allocateSize, validity->period);
+ }
+
+ if(validity->recurrences && 0 < validity->recurrenceLen)
+ {
+ newValidity->recurrenceLen = validity->recurrenceLen;
+
+ newValidity->recurrences = (char**)OICMalloc(sizeof(char*) * validity->recurrenceLen);
+ VERIFY_NON_NULL(TAG, newValidity->recurrences, ERROR);
+
+ for(size_t i = 0; i < validity->recurrenceLen; i++)
+ {
+ allocateSize = strlen(validity->recurrences[i]) + 1;
+ newValidity->recurrences[i] = (char*)OICMalloc(sizeof(char) * allocateSize);
+ VERIFY_NON_NULL(TAG, (newValidity->recurrences[i]), ERROR);
+ OICStrcpy(newValidity->recurrences[i], allocateSize, validity->recurrences[i]);
+ }
+ }
+ }
}
+
+ newAce->next = NULL;
}
+
+ return newAce;
+
+exit:
+ FreeACE(newAce);
+ return NULL;
}
static size_t OicSecAclSize(const OicSecAcl_t *secAcl)
{
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;
}
OCStackResult ret = OC_STACK_ERROR;
CborError cborEncoderResult = CborNoError;
OicSecAcl_t *acl = (OicSecAcl_t *)secAcl;
+ OicSecAce_t* ace = NULL;
CborEncoder encoder;
CborEncoder aclMap;
CborEncoder aclListMap;
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);
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)
{
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);
}
strlen(OIC_JSON_RESOURCES_NAME));
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Tag.");
- cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &resources, acl->resourcesLen);
+ size_t rsrcLen = 0;
+ OicSecRsrc_t* rsrcElts = NULL;
+ LL_FOREACH(ace->resources, rsrcElts)
+ {
+ rsrcLen++;
+ }
+
+ cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &resources, rsrcLen);
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Array.");
- for (size_t i = 0; i < acl->resourcesLen; i++)
+ OicSecRsrc_t* rsrc = NULL;
+ LL_FOREACH(ace->resources, rsrc)
{
CborEncoder rMap;
cborEncoderResult = cbor_encoder_create_map(&resources, &rMap, ACL_RESOURCE_MAP_SIZE);
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Resource Map.");
+ //href -- Mandatory
+ VERIFY_NON_NULL(TAG, rsrc->href, ERROR);
cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_HREF_NAME,
strlen(OIC_JSON_HREF_NAME));
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding HREF Name Tag.");
- cborEncoderResult = cbor_encode_text_string(&rMap, acl->resources[i],
- strlen(acl->resources[i]));
+ cborEncoderResult = cbor_encode_text_string(&rMap, rsrc->href, strlen(rsrc->href));
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding HREF Value in Map.");
- cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_REL_NAME,
- strlen(OIC_JSON_REL_NAME));
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Name Tag.");
-
- // TODO : Need to assign real value of REL
- cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
- strlen(OIC_JSON_EMPTY_STRING));
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Value.");
-
+ //resource type -- Mandatory
cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_RT_NAME,
strlen(OIC_JSON_RT_NAME));
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
- // TODO : Need to assign real value of RT
- cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
- strlen(OIC_JSON_EMPTY_STRING));
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
+ CborEncoder resourceTypes;
+ cborEncoderResult = cbor_encoder_create_array(&rMap, &resourceTypes, rsrc->typeLen);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Array.");
+ for(size_t i = 0; i < rsrc->typeLen; i++)
+ {
+ cborEncoderResult = cbor_encode_text_string(&resourceTypes, rsrc->types[i], strlen(rsrc->types[i]));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
+ }
+ cborEncoderResult = cbor_encoder_close_container(&rMap, &resourceTypes);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing resourceTypes.");
+ //interface -- Mandatory
cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_IF_NAME,
strlen(OIC_JSON_IF_NAME));
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
- // TODO : Need to assign real value of IF
- cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
- strlen(OIC_JSON_EMPTY_STRING));
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
+ CborEncoder interfaces;
+ cborEncoderResult = cbor_encoder_create_array(&rMap, &interfaces, rsrc->interfaceLen);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Array.");
+ for(size_t i = 0; i < rsrc->interfaceLen; i++)
+ {
+ cborEncoderResult = cbor_encode_text_string(&interfaces, rsrc->interfaces[i], strlen(rsrc->interfaces[i]));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
+ }
+ cborEncoderResult = cbor_encoder_close_container(&rMap, &interfaces);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing interfaces.");
+ //rel
+ if(rsrc->rel)
+ {
+ cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_REL_NAME,
+ strlen(OIC_JSON_REL_NAME));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Name Tag.");
+ cborEncoderResult = cbor_encode_text_string(&rMap, rsrc->rel, strlen(rsrc->rel));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Value.");
+ }
+ else
+ {
+ cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_REL_NAME,
+ strlen(OIC_JSON_REL_NAME));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Name Tag.");
+ cborEncoderResult = cbor_encode_text_string(&rMap, "", 0);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Value.");
+ }
cborEncoderResult = cbor_encoder_close_container(&resources, &rMap);
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Map.");
-
}
cborEncoderResult = cbor_encoder_close_container(&oicSecAclMap, &resources);
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Name Array.");
}
-
// Permissions -- Mandatory
cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_PERMISSION_NAME,
strlen(OIC_JSON_PERMISSION_NAME));
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Permission Name Tag.");
- cborEncoderResult = cbor_encode_int(&oicSecAclMap, acl->permission);
+ cborEncoderResult = cbor_encode_int(&oicSecAclMap, ace->permission);
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Permission Name Value.");
- // Period -- Not Mandatory
- if (acl->periods)
+ // TODO: Need to verfication for validity
+ // Validity(Time-interval) -- Not Mandatory
+ if(ace->validities)
{
-
- CborEncoder period;
- cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_PERIOD_NAME,
- strlen(OIC_JSON_PERIOD_NAME));
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Tag.");
- cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &period, acl->prdRecrLen);
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Array.");
- for (size_t i = 0; i < acl->prdRecrLen; i++)
+ size_t validityLen = 0;
+ validityElts = NULL;
+ LL_FOREACH(ace->validities, validityElts)
{
- cborEncoderResult = cbor_encode_text_string(&period, acl->periods[i],
- strlen(acl->periods[i]));
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Value in Array.");
+ validityLen++;
}
- cborEncoderResult = cbor_encoder_close_container(&oicSecAclMap, &period);
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Period Array.");
- }
- // Recurrence -- Not Mandatory
- if (acl->recurrences)
- {
- CborEncoder recurrences;
- cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_RECURRENCES_NAME,
- strlen(OIC_JSON_RECURRENCES_NAME));
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Tag.");
- cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &recurrences, acl->prdRecrLen);
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array.");
-
- for (size_t i = 0; i < acl->prdRecrLen; i++)
+ CborEncoder validities;
+ cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_VALIDITY_NAME,
+ strlen(OIC_JSON_VALIDITY_NAME));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Validity Tag.");
+ cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &validities, validityLen);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Validities Array.");
+
+ //How to add the value w/o "title" using tinycobr...? :(
+
+ validityElts = NULL;
+ LL_FOREACH(ace->validities, validityElts)
{
- cborEncoderResult = cbor_encode_text_string(&recurrences, acl->recurrences[i],
- strlen(acl->recurrences[i]));
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array Value.");
+ CborEncoder validity;
+ size_t validitySize = 0;
+ if(validityElts->period)
+ {
+ validitySize++;
+ }
+ if(validityElts->recurrences)
+ {
+ validitySize++;
+ }
+
+ cborEncoderResult = cbor_encoder_create_array(&validities, &validity, validitySize);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Validity Array.");
+
+ // Period
+ if (validityElts->period)
+ {
+ cborEncoderResult = cbor_encode_text_string(&validity, validityElts->period,
+ strlen(validityElts->period));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Value.");
+ }
+
+ // Recurrence
+ if (validityElts->recurrences)
+ {
+ CborEncoder recurrences;
+ cborEncoderResult = cbor_encoder_create_array(&validity, &recurrences, validityElts->recurrenceLen);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array.");
+
+ for (size_t i = 0; i < validityElts->recurrenceLen; i++)
+ {
+ cborEncoderResult = cbor_encode_text_string(&recurrences, validityElts->recurrences[i],
+ strlen(validityElts->recurrences[i]));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array Value.");
+ }
+ cborEncoderResult = cbor_encoder_close_container(&validity, &recurrences);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Recurrence Array");
+ }
+
+ cborEncoderResult = cbor_encoder_close_container(&validities, &validity);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Validity Array.");
}
- cborEncoderResult = cbor_encoder_close_container(&oicSecAclMap, &recurrences);
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Recurrence Array");
+ cborEncoderResult = cbor_encoder_close_container(&oicSecAclMap, &validities);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Validities Array.");
}
-
cborEncoderResult = cbor_encoder_close_container(&acesArray, &oicSecAclMap);
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACES Map.");
- acl = acl->next;
}
// Close ACES Array
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 };
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)
{
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);
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
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))
{
// "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))
// 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.");
}
}
}
}
- // 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);
}
if (cborFindResult != CborNoError)
{
OIC_LOG(ERROR, TAG, "Failed to CBORPayloadToAcl");
- DeleteACLList(headAcl);
- headAcl = NULL;
+ DeleteACLList(acl);
+ acl = NULL;
}
- return headAcl;
+
+ return acl;
}
/**
{
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;
//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;
}
}
//resource in the ACE for the subject then delete the whole ACE. If there are more resources
//than the required resource in the ACE, for the subject then just delete the resource from
//the resource array
- LL_FOREACH_SAFE(gAcl, acl, tempAcl)
+ LL_FOREACH_SAFE(gAcl->aces, ace, tempAce)
{
- if (memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
+ if (memcmp(ace->subjectuuid.id, subject->id, sizeof(subject->id)) == 0)
{
- if (1 == acl->resourcesLen && strcmp(acl->resources[0], resource) == 0)
+ OicSecRsrc_t* rsrc = NULL;
+ OicSecRsrc_t* tempRsrc = NULL;
+ LL_FOREACH_SAFE(ace->resources, rsrc, tempRsrc)
{
- LL_DELETE(gAcl, acl);
- FreeACE(acl);
- deleteFlag = true;
- break;
- }
- else
- {
- size_t resPos = -1;
- size_t i;
- for (i = 0; i < acl->resourcesLen; i++)
+ if(strcmp(rsrc->href, resource) == 0)
{
- if (strcmp(acl->resources[i], resource) == 0)
- {
- resPos = i;
- break;
- }
- }
- if (0 <= (int) resPos)
- {
- OICFree(acl->resources[resPos]);
- acl->resources[resPos] = NULL;
- acl->resourcesLen -= 1;
- for (i = resPos; i < acl->resourcesLen; i++)
- {
- acl->resources[i] = acl->resources[i + 1];
- }
+ LL_DELETE(ace->resources, rsrc);
+ FreeRsrc(rsrc);
deleteFlag = true;
- break;
}
}
+
+ //If resource list is empty
+ if(NULL == ace->resources && true == deleteFlag)
+ {
+ //Remove the ACE from ACL
+ LL_DELETE(gAcl->aces, ace);
+ FreeACE(ace);
+ }
}
}
}
{
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;
}
}
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));
/*
*/
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;
}
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;
}
}
}
}
+ // 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))
{
if (newAcl)
{
// Append the new ACL to existing ACL
- LL_APPEND(gAcl, newAcl);
- size_t size = 0;
- // In case of unit test do not update persistant storage.
- if (memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_ID, sizeof(newAcl->subject.id)) == 0
- || memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_B64_ID, sizeof(newAcl->subject.id)) == 0)
+ OicSecAce_t* newAce = NULL;
+ OicSecAce_t* tempAce = NULL;
+ LL_FOREACH_SAFE(newAcl->aces, newAce, tempAce)
{
- ehRet = OC_EH_RESOURCE_CREATED;
+ LL_APPEND(gAcl->aces, newAce);
}
- else
+ newAcl->aces = NULL;
+
+ size_t size = 0;
+ uint8_t *cborPayload = NULL;
+ if (OC_STACK_OK == AclToCBORPayload(gAcl, &cborPayload, &size))
{
- uint8_t *cborPayload = NULL;
- if (OC_STACK_OK == AclToCBORPayload(gAcl, &cborPayload, &size))
+ if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, cborPayload, size) == OC_STACK_OK)
{
- if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, cborPayload, size) == OC_STACK_OK)
- {
- ehRet = OC_EH_RESOURCE_CREATED;
- }
- OICFree(cborPayload);
+ ehRet = OC_EH_RESOURCE_CREATED;
}
+ OICFree(cborPayload);
}
}
+
+ DeleteACLList(newAcl);
}
// Send payload to request originator
ret = OCCreateResource(&gAclHandle,
OIC_RSRC_TYPE_SEC_ACL,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_ACL_URI,
ACLEntityHandler,
NULL,
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
* 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)
memcpy(&acl->rownerID, &ownerId, sizeof(OicUuid_t));
- acl->next = NULL;
-
*defaultAcl = acl;
ret = OC_STACK_OK;
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");
}
*/
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);
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)
{
*/
if (NULL == *savePtr)
{
- begin = gAcl;
+ begin = gAcl->aces;
}
else
{
* 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;
}
}
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);
}
}
}
/**
- * This function generates default ACL for security resource in case of owned status.
+ * This function generates default ACE for security resource in case of owned status.
*
- * @return Default ACL for security resource.
+ * @return Default ACE for security resource.
*/
-static OicSecAcl_t* GetSecDefaultACL()
+static OicSecAce_t* GetSecDefaultACE()
{
- const char *sec_rsrcs[] = {
- OIC_RSRC_DOXM_URI,
- OIC_RSRC_PSTAT_URI
- };
- OicUuid_t ownerId = {.id = {0}};
- OCStackResult res = OC_STACK_ERROR;
- OicSecAcl_t* newDefaultAcl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
- VERIFY_NON_NULL(TAG, newDefaultAcl, ERROR);
+ const int NUM_OF_DOXM_RT = 1;
+ const int NUM_OF_DOXM_IF = 1;
+ const int NUM_OF_PSTAT_RT = 1;
+ const int NUM_OF_PSTAT_IF = 1;
+ const char *doxmRt[] = { OIC_RSRC_TYPE_SEC_DOXM };
+ const char *pstatRt[] = { OIC_RSRC_TYPE_SEC_PSTAT };
+ const char *doxmIf[] = { OC_RSRVD_INTERFACE_DEFAULT };
+ const char *pstatIf[] = { OC_RSRVD_INTERFACE_DEFAULT };
+ OicSecRsrc_t* doxmRsrc = NULL;
+ OicSecRsrc_t* pstatRsrc = NULL;
+
+ //Generate default ACE
+ OicSecAce_t* newAce = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+ VERIFY_NON_NULL(TAG, newAce, ERROR);
// Subject -- Mandatory
- memcpy(&(newDefaultAcl->subject), &WILDCARD_SUBJECT_ID, WILDCARD_SUBJECT_ID_LEN);
-
- // Resources -- Mandatory
- newDefaultAcl->resourcesLen = NUMBER_OF_DEFAULT_SEC_RSCS;
- newDefaultAcl->resources = (char**)OICCalloc(NUMBER_OF_DEFAULT_SEC_RSCS, sizeof(char*));
- VERIFY_NON_NULL(TAG, (newDefaultAcl->resources), ERROR);
+ memcpy(newAce->subjectuuid.id, &WILDCARD_SUBJECT_ID, WILDCARD_SUBJECT_ID_LEN);
+
+ //Resources -- Mandatory
+ //Add doxm
+ doxmRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+ VERIFY_NON_NULL(TAG, doxmRsrc, ERROR);
+ LL_APPEND(newAce->resources, doxmRsrc);
+ // pstat-href
+ doxmRsrc->href = OICStrdup(OIC_RSRC_DOXM_URI);
+ VERIFY_NON_NULL(TAG, (doxmRsrc->href), ERROR);
+ // pstat-rt
+ doxmRsrc->typeLen = NUM_OF_DOXM_RT;
+ doxmRsrc->types = (char**)OICCalloc(NUM_OF_DOXM_RT, sizeof(char*));
+ VERIFY_NON_NULL(TAG, (doxmRsrc->types), ERROR);
+ for(int i = 0; i < NUM_OF_DOXM_RT; i++)
+ {
+ doxmRsrc->types[i] = OICStrdup(doxmRt[i]);
+ VERIFY_NON_NULL(TAG, (doxmRsrc->types[i]), ERROR);
+ }
+ // pstat-if
+ doxmRsrc->interfaceLen = NUM_OF_DOXM_IF;
+ doxmRsrc->interfaces = (char**)OICCalloc(NUM_OF_DOXM_IF, sizeof(char*));
+ VERIFY_NON_NULL(TAG, (doxmRsrc->interfaces), ERROR);
+ for(int i = 0; i < NUM_OF_DOXM_IF; i++)
+ {
+ doxmRsrc->interfaces[i] = OICStrdup(doxmIf[i]);
+ VERIFY_NON_NULL(TAG, (doxmRsrc->interfaces[i]), ERROR);
+ }
- for (size_t i = 0; i < NUMBER_OF_DEFAULT_SEC_RSCS; i++)
+ //Add pstat
+ pstatRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+ VERIFY_NON_NULL(TAG, pstatRsrc, ERROR);
+ LL_APPEND(newAce->resources, pstatRsrc);
+ //pstat-href
+ pstatRsrc->href = OICStrdup(OIC_RSRC_PSTAT_URI);
+ VERIFY_NON_NULL(TAG, (pstatRsrc->href), ERROR);
+ //pstat-rt
+ pstatRsrc->typeLen = NUM_OF_PSTAT_RT;
+ pstatRsrc->types = (char**)OICCalloc(NUM_OF_PSTAT_RT, sizeof(char*));
+ VERIFY_NON_NULL(TAG, (pstatRsrc->types), ERROR);
+ for(int i = 0; i < NUM_OF_PSTAT_RT; i++)
{
- size_t len = strlen(sec_rsrcs[i]) + 1;
- newDefaultAcl->resources[i] = (char*)OICMalloc(len * sizeof(char));
- VERIFY_NON_NULL(TAG, (newDefaultAcl->resources[i]), ERROR);
- OICStrcpy(newDefaultAcl->resources[i], len, sec_rsrcs[i]);
+ pstatRsrc->types[i] = OICStrdup(pstatRt[i]);
+ VERIFY_NON_NULL(TAG, (pstatRsrc->types[i]), ERROR);
+ }
+ // pstat-if
+ pstatRsrc->interfaceLen = NUM_OF_PSTAT_IF;
+ pstatRsrc->interfaces = (char**)OICCalloc(NUM_OF_PSTAT_IF, sizeof(char*));
+ VERIFY_NON_NULL(TAG, (pstatRsrc->interfaces), ERROR);
+ for(int i = 0; i < NUM_OF_PSTAT_IF; i++)
+ {
+ pstatRsrc->interfaces[i] = OICStrdup(pstatIf[i]);
+ VERIFY_NON_NULL(TAG, (pstatRsrc->interfaces[i]), ERROR);
}
// Permissions -- Mandatory
- newDefaultAcl->permission = PERMISSION_READ;
+ newAce->permission = PERMISSION_READ;
//Period -- Not Mandatory
- newDefaultAcl->prdRecrLen = 0;
- newDefaultAcl->periods = NULL;
-
- //Recurrence -- Not Mandatory
- newDefaultAcl->recurrences = NULL;
-
- // Device ID is the owner of this default ACL
- res = GetDoxmDeviceID(&ownerId);
- VERIFY_SUCCESS(TAG, OC_STACK_OK == res, FATAL);
-
- // Owners -- Mandatory
- memcpy(&newDefaultAcl->rownerID, &ownerId, sizeof(OicUuid_t));
+ newAce->validities = NULL;
- return newDefaultAcl;
+ return newAce;
exit:
- DeleteACLList(newDefaultAcl);
+ FreeACE(newAce);
return NULL;
}
-OCStackResult UpdateDefaultSecProvACL()
+OCStackResult UpdateDefaultSecProvACE()
{
OCStackResult ret = OC_STACK_OK;
- OicSecAcl_t *acl = NULL;
- OicSecAcl_t *tmp = NULL;
+ OicSecAce_t *ace = NULL;
+ OicSecAce_t *tempAce = NULL;
if(gAcl)
{
int matchedRsrc = 0;
bool isRemoved = false;
- LL_FOREACH_SAFE(gAcl, acl, tmp)
+ LL_FOREACH_SAFE(gAcl->aces, ace, tempAce)
{
//Find default security resource ACL
- if(memcmp(&acl->subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0 &&
- ((PERMISSION_READ | PERMISSION_WRITE) == acl->permission))
+ if(memcmp(&ace->subjectuuid, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0 &&
+ ((PERMISSION_READ | PERMISSION_WRITE) == ace->permission))
{
matchedRsrc = 0;
- for(size_t i = 0; i < acl->resourcesLen; i++)
+ OicSecRsrc_t* rsrc = NULL;
+ LL_FOREACH(ace->resources, rsrc)
{
- if(strncmp(acl->resources[i], OIC_RSRC_DOXM_URI,
+ if(strncmp(rsrc->href, OIC_RSRC_DOXM_URI,
strlen(OIC_RSRC_DOXM_URI) + 1) == 0 ||
- strncmp(acl->resources[i], OIC_RSRC_CRED_URI,
+ strncmp(rsrc->href, OIC_RSRC_CRED_URI,
strlen(OIC_RSRC_CRED_URI) + 1) == 0 ||
- strncmp(acl->resources[i], OIC_RSRC_ACL_URI,
+ strncmp(rsrc->href, OIC_RSRC_ACL_URI,
strlen(OIC_RSRC_ACL_URI) + 1) == 0 ||
- strncmp(acl->resources[i], OIC_RSRC_PSTAT_URI,
+ strncmp(rsrc->href, OIC_RSRC_PSTAT_URI,
strlen(OIC_RSRC_PSTAT_URI) + 1) == 0)
{
matchedRsrc++;
//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;
}
}
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;
}
}
-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)
{
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;
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;
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;
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);
}
// 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);
{
OCStackResult ret = OCCreateResource(&gAmaclHandle,
OIC_RSRC_TYPE_SEC_AMACL,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_AMACL_URI,
AmaclEntityHandler,
NULL,
OCStackResult ret = OC_STACK_ERROR;
const char DOXM_DEVICEID_QUERY_FMT[] = "%s?%s=%s";
- char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
+ char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
OCCallbackData cbData = {.context=NULL};
VERIFY_NON_NULL(TAG, context, ERROR);
return OC_STACK_KEEP_TRANSACTION;
}
- OicUuid_t deviceId = {.id={}};
+ OicUuid_t deviceId = {.id={0}};
memcpy(&deviceId, &doxm->deviceID, sizeof(deviceId));
OICFree(doxm);
const char RES_DOXM_QUERY_FMT[] = "%s?%s=%s";
OCCallbackData cbData = {.context=NULL};
- char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
+ char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
snprintf(uri, sizeof(uri), RES_DOXM_QUERY_FMT, OC_RSRVD_WELL_KNOWN_URI,
OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DOXM);
{
OCStackResult ret = OC_STACK_ERROR;
const char GET_ACE_QUERY_FMT[] = "%s?%s=%s;%s=%s";
- char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
- uint32_t outLen = 0;
- char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
+ char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
OCCallbackData cbData = {.context=NULL};
OCDevAddr destAddr = {.adapter = OC_ADAPTER_IP};
- B64Result b64Ret;
char *subID = NULL;
VERIFY_NON_NULL(TAG, context, ERROR);
void ProcessAMSRequest(PEContext_t *context)
{
- OicUuid_t emptyUuid = {.id={}};
+ OicUuid_t emptyUuid = {.id={0}};
OIC_LOG_V(INFO, TAG, "Entering %s", __func__);
if (NULL != context)
{
#define __STDC_LIMIT_MACROS
#include <stdlib.h>
-#ifdef WITH_ARDUINO
+#ifdef HAVE_STRING_H
#include <string.h>
-#else
+#endif
+#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#include <stdint.h>
}
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)
{
mapSize++;
}
#endif /* __WITH_X509__ */
- if (cred->privateData.data)
+ if (!secureFlag && cred->privateData.data)
{
mapSize++;
}
}
#endif /*__WITH_X509__*/
//PrivateData -- Not Mandatory
- if(cred->privateData.data)
+ if(!secureFlag && cred->privateData.data)
{
CborEncoder privateMap;
const size_t privateMapSize = 2;
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.");
// 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;
}
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.");
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);
//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)
// 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)
{
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);
// 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))
{
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);
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);
}
//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);
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);
{
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))
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");
#endif //__WITH_DTLS__
-static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
{
OCEntityHandlerResult ret = OC_EH_ERROR;
- OIC_LOG(DEBUG, TAG, "HandleCREDPutRequest IN");
+ OIC_LOG(DEBUG, TAG, "HandleCREDPostRequest IN");
//Get binary representation of cbor
OicSecCred_t *cred = NULL;
uint8_t *payload = (((OCSecurityPayload*)ehRequest->payload)->securityData);
size_t size = (((OCSecurityPayload*)ehRequest->payload)->payloadSize);
+
OCStackResult res = CBORPayloadToCred(payload, size, &cred);
if (res == OC_STACK_OK)
{
#ifdef __WITH_DTLS__
OicUuid_t emptyUuid = {.id={0}};
const OicSecDoxm_t* doxm = GetDoxmResourceData();
- if(false == doxm->owned && memcmp(&(doxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0)
+ if(doxm && false == doxm->owned && memcmp(&(doxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0)
{
//in case of owner PSK
switch(cred->credType)
}
FreeCred(cred);
}
- OIC_LOG(DEBUG, TAG, "HandleCREDPutRequest OUT");
+ OIC_LOG(DEBUG, TAG, "HandleCREDPostRequest OUT");
return ret;
}
-static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
+/**
+ * The entity handler determines how to process a GET request.
+ */
+static OCEntityHandlerResult HandleGetRequest (const OCEntityHandlerRequest * ehRequest)
{
- OCEntityHandlerResult ret = OC_EH_ERROR;
+ OIC_LOG(INFO, TAG, "HandleGetRequest processing GET request");
- //Get binary representation of CBOR
- OicSecCred_t *cred = NULL;
- uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData;
- size_t size = ((OCSecurityPayload*)ehRequest->payload)->payloadSize;
- OCStackResult res = CBORPayloadToCred(payload, size, &cred);
- if ((OC_STACK_OK == res) && cred)
+ // Convert Cred data into CBOR for transmission
+ size_t size = 0;
+ uint8_t *payload = NULL;
+ int secureFlag = 1;
+
+ const OicSecCred_t *cred = gCred;
+ OCStackResult res = CredToCBORPayload(cred, &payload, &size, secureFlag);
+
+ // A device should always have a default cred. Therefore, payload should never be NULL.
+ OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
+
+ // Send response payload to request originator
+ if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, payload, size))
{
- //If the Post request credential has credId, it will be
- //discarded and the next available credId will be assigned
- //to it before getting appended to the existing credential
- //list and updating svr database.
- ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_RESOURCE_CREATED : OC_EH_ERROR;
+ ehRet = OC_EH_ERROR;
+ OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandlePstatGetRequest");
}
-
- return ret;
+ OICFree(payload);
+ return ehRet;
}
static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *ehRequest)
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;
{
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)
{
case CA_DTLS_PSK_HINT:
case CA_DTLS_PSK_IDENTITY:
{
- OicUuid_t deviceID = {.id={}};
+ OicUuid_t deviceID = {.id={0}};
// Retrieve Device ID from doxm resource
if ( OC_STACK_OK != GetDoxmDeviceID(&deviceID) )
{
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;
}
}
}
default:
{
OIC_LOG (ERROR, TAG, "Wrong value passed for CADtlsPskCredType_t.");
- ret = -1;
}
break;
}
}
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,
OCStackResult ret = OC_STACK_ERROR;
uint8_t *cborPayload = NULL;
size_t size = 0;
+ int secureFlag = 0;
OicUuid_t prevId = {.id={0}};
if(NULL == 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);
{
OCStackResult ret = OCCreateResource(&gCrlHandle,
OIC_RSRC_TYPE_SEC_CRL,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_CRL_URI,
CRLEntityHandler,
NULL,
/**
* 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()
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);
}
#ifndef _POSIX_C_SOURCE\r
#define _POSIX_C_SOURCE 200112L\r
#endif\r
-#ifndef WITH_ARDUINO\r
+#ifdef HAVE_UNISTD_H\r
#include <unistd.h>\r
+#endif\r
+#ifdef HAVE_TIME_H\r
#include <time.h>\r
+#endif\r
+#ifdef HAVE_SYS_TIME_H\r
#include <sys/time.h>\r
#endif\r
+#ifdef HAVE_STRING_H\r
#include <string.h>\r
+#endif\r
\r
#include "ocstack.h"\r
#include "oic_malloc.h"\r
OCDirectPairingDev_t *peer; /**< Pointer to pairing target info.**/\r
char pin[DP_PIN_LENGTH]; /**< PIN **/\r
OCDirectPairingResultCB resultCallback; /**< Pointer to result callback.**/\r
+ void *userCtx; /** < user context to pass in callback **/\r
} DPairData_t;\r
\r
static OCDirectPairingDev_t *g_dp_paired = NULL;\r
if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))\r
{\r
OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");\r
- resultCallback(peer, OC_STACK_ERROR);\r
+ resultCallback(dpairData->userCtx, peer, OC_STACK_ERROR);\r
return OC_STACK_DELETE_TRANSACTION;\r
}\r
\r
if(OC_STACK_OK != res)\r
{\r
OIC_LOG(ERROR, TAG, "Failed to PairingPSK generation");\r
- resultCallback(peer, res);\r
+ resultCallback(dpairData->userCtx, peer, res);\r
return OC_STACK_DELETE_TRANSACTION;\r
}\r
\r
OIC_LOG(ERROR, TAG, "Error while adding a device to paired list.");\r
}\r
\r
- resultCallback(peer, OC_STACK_OK);\r
+ resultCallback(dpairData->userCtx, peer, OC_STACK_OK);\r
\r
return OC_STACK_DELETE_TRANSACTION;\r
}\r
OIC_LOG(ERROR, TAG, "DirectPairingFinalizeHandler received Null clientResponse");\r
}\r
\r
- resultCallback(peer, OC_STACK_ERROR);\r
+ resultCallback(dpairData->userCtx, peer, OC_STACK_ERROR);\r
OICFree(dpairData);\r
return OC_STACK_DELETE_TRANSACTION;\r
}\r
*\r
* @return OC_STACK_OK on success otherwise error.\r
*/\r
-OCStackResult FinalizeDirectPairing(OCDirectPairingDev_t* peer,\r
+OCStackResult FinalizeDirectPairing(void *ctx, OCDirectPairingDev_t* peer,\r
OCDirectPairingResultCB resultCallback)\r
{\r
if(NULL == peer)\r
}\r
dpairData->peer = peer;\r
dpairData->resultCallback = resultCallback;\r
+ dpairData->userCtx = ctx;\r
\r
OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};\r
cbData.cb = DirectPairingFinalizeHandler;\r
{\r
OIC_LOG(INFO, TAG, "Now, finalize Direct-Pairing procedure.");\r
\r
- res = FinalizeDirectPairing(peer, resultCallback);\r
+ res = FinalizeDirectPairing(g_dp_proceed_ctx->userCtx, peer, resultCallback);\r
if(OC_STACK_OK != res)\r
{\r
OIC_LOG(ERROR, TAG, "Failed to finalize direct-pairing");\r
- resultCallback(peer, res);\r
+ resultCallback(g_dp_proceed_ctx->userCtx, peer, res);\r
}\r
}\r
else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)\r
{\r
OIC_LOG(INFO, TAG, "DirectPairingDTLSHandshakeCB - Authentication failed");\r
- resultCallback(peer, OC_STACK_AUTHENTICATION_FAILURE);\r
+ resultCallback(g_dp_proceed_ctx->userCtx, peer, OC_STACK_AUTHENTICATION_FAILURE);\r
}\r
\r
#ifdef __WITH_DTLS__\r
g_dp_proceed_ctx = NULL;\r
}\r
\r
- resultCallback(dpairData->peer, res);\r
+ resultCallback(dpairData->userCtx, dpairData->peer, res);\r
}\r
OIC_LOG_V(INFO, TAG, "OUT DirectPairingHandler.");\r
return OC_STACK_DELETE_TRANSACTION;\r
*\r
* @return OC_STACK_OK on success otherwise error.\r
*/\r
-OCStackResult DPDirectPairing(OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, char *pinNumber,\r
- OCDirectPairingResultCB resultCallback)\r
+OCStackResult DPDirectPairing(void *ctx, OCDirectPairingDev_t* peer, OicSecPrm_t pmSel,\r
+ char *pinNumber, OCDirectPairingResultCB resultCallback)\r
{\r
if(NULL == peer || NULL == pinNumber)\r
{\r
dpairData->peer = peer;\r
memcpy(dpairData->pin, pinNumber, DP_PIN_LENGTH);\r
dpairData->resultCallback = resultCallback;\r
+ dpairData->userCtx = ctx;\r
\r
OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};\r
cbData.cb = DirectPairingHandler;\r
}\r
\r
OCStackResult ret;\r
- struct timespec startTime = {.tv_sec=0, .tv_nsec=0};\r
- struct timespec currTime = {.tv_sec=0, .tv_nsec=0};\r
- struct timespec timeout;\r
\r
const char DP_DISCOVERY_QUERY[] = "/oic/sec/pconf";\r
\r
}\r
\r
// wait..\r
- timeout.tv_sec = 0;\r
- timeout.tv_nsec = 100000000L;\r
\r
int clock_res = -1;\r
+#if defined(_MSC_VER)\r
+ time_t startTime = NULL;\r
+ clock_res = (time(&startTime) == -1);\r
+#else\r
+ struct timespec startTime = {.tv_sec=0, .tv_nsec=0};\r
#if defined(__ANDROID__) || _POSIX_TIMERS > 0\r
clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);\r
#endif\r
+#endif\r
if (0 != clock_res)\r
{\r
OIC_LOG(ERROR, TAG, "clock error");\r
\r
while (1)\r
{\r
+#if defined(_MSC_VER)\r
+ time_t currTime = NULL;\r
+ clock_res = (time(&currTime) == -1);\r
+#else\r
+ struct timespec currTime = {.tv_sec=0, .tv_nsec=0};\r
#if defined(__ANDROID__) || _POSIX_TIMERS > 0\r
clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);\r
#endif\r
+#endif\r
if (0 != clock_res)\r
{\r
OIC_LOG(ERROR, TAG, "clock error");\r
ret = OC_STACK_ERROR;\r
break;\r
}\r
+#if defined(_MSC_VER)\r
+ long elapsed = currTime - startTime;\r
+#else\r
long elapsed = (currTime.tv_sec - startTime.tv_sec);\r
+#endif\r
if (elapsed > waittime)\r
{\r
break;\r
}\r
else\r
{\r
+ struct timespec timeout = {.tv_sec=0, .tv_nsec=100000000L};\r
+ OCProcess();\r
nanosleep(&timeout, NULL);\r
}\r
}\r
\r
- //Waiting for each response.\r
+ // Waiting for each response.\r
ret = OCCancel(handle, OC_LOW_QOS, NULL, 0);\r
if (OC_STACK_OK != ret)\r
{\r
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;
OICFree(strUuid);
strUuid = NULL;
- //DPC -- not Mandatory, but this type is boolean, so instance always has a value.
+ //x.com.samsung.dpc -- not Mandatory(vendor-specific), but this type is boolean, so instance always has a value.
cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DPC_NAME,
strlen(OIC_JSON_DPC_NAME));
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Tag.");
cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->dpc);
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Value.");
+ //RT -- Mandatory
+ CborEncoder rtArray;
+ cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
+ strlen(OIC_JSON_RT_NAME));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
+ cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
+ for (size_t i = 0; i < 1; i++)
+ {
+ cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
+ strlen(OIC_RSRC_TYPE_SEC_DOXM));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
+ }
+ cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
+
+ //IF-- Mandatory
+ CborEncoder ifArray;
+ cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
+ strlen(OIC_JSON_IF_NAME));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
+ cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
+ for (size_t i = 0; i < 1; i++)
+ {
+ cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
+ strlen(OC_RSRVD_INTERFACE_DEFAULT));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
+ }
+ cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
+
cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
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);
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")
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};
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));
//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))
{
{
if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size))
{
- payload = NULL;
+ OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
}
}
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
caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
- char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
- if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
+ if(previousMsgId != ehRequest->messageID)
{
- //Set the device id to derive temporal PSK
- SetUuidForRandomPinOxm(&gDoxm->deviceID);
-
- /**
- * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
- * Credential should not be saved into SVR.
- * For this reason, use a temporary get_psk_info callback to random PIN OxM.
- */
- caRes = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm);
- VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
- ehRet = OC_EH_OK;
- }
- else
- {
- OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
- ehRet = OC_EH_ERROR;
+ char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
+ if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
+ {
+ //Set the device id to derive temporal PSK
+ SetUuidForRandomPinOxm(&gDoxm->deviceID);
+
+ /**
+ * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
+ * Credential should not be saved into SVR.
+ * For this reason, use a temporary get_psk_info callback to random PIN OxM.
+ */
+ caRes = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm);
+ VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
+ ehRet = OC_EH_OK;
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
+ ehRet = OC_EH_ERROR;
+ }
+ previousMsgId = ehRequest->messageID;
}
#endif //__WITH_DTLS__
}
// 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;
}
ehRet = HandleDoxmGetRequest(ehRequest);
break;
- case OC_REST_PUT:
- ehRet = HandleDoxmPutRequest(ehRequest);
+ case OC_REST_POST:
+ ehRet = HandleDoxmPostRequest(ehRequest);
break;
default:
{
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)
{
#include "ocpayload.h"
#include "payload_logging.h"
#include <stdlib.h>
-#ifdef WITH_ARDUINO
-#include <string.h>
-#else
+#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
}
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,
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;
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");
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
ret = OCCreateResource(&gDpairHandle,
OIC_RSRC_TYPE_SEC_DPAIRING,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_DPAIRING_URI,
DpairingEntityHandler,
NULL,
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//Not supported on Arduino due lack of absolute time need to implement iCalendar
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO)
#define _XOPEN_SOURCE //Needed by strptime
#include <string.h>
#include "iotvticalendar.h"
#include "oic_string.h"
+#ifndef HAVE_STRPTIME
+char *strptime(const char *buf, const char *fmt, struct tm *tm);
+#endif
+
static char dtFormat[] = "%Y%m%dT%H%M%S"; //date-time format
static char dFormat[] = "%Y%m%d"; // date format
#include <string.h>
#include <math.h>
+#include "platform_features.h"
#include "pbkdf2.h"
#include "hmac.h"
#include "debug.h"
#include <stdlib.h>
#include "psinterface.h"
#include "security_internals.h"
-#ifdef WITH_ARDUINO
-#include <string.h>
-#else
+#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
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");
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");
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");
}
}
//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);
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);
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 };
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;
}
// 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 };
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);
}
// 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 };
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);
}
//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 };
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);
}
//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);
}
// 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);
ret = OCCreateResource(&gPconfHandle,
OIC_RSRC_TYPE_SEC_PCONF,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_PCONF_URI,
PconfEntityHandler,
NULL,
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <string.h>
+#include "utlist.h"
#include "oic_malloc.h"
#include "policyengine.h"
#include "amsmgr.h"
return retVal;
}
-inline static bool IsRequestSubjectEmpty(PEContext_t *context)
+INLINE_API bool IsRequestSubjectEmpty(PEContext_t *context)
{
- OicUuid_t emptySubject = {.id={}};
+ OicUuid_t emptySubject = {.id={0}};
if(NULL == context)
{
*
* @return true if 'permission' bits include all 'request' bits.
*/
-static inline bool IsPermissionAllowingRequest(const uint16_t permission,
+INLINE_API bool IsPermissionAllowingRequest(const uint16_t permission,
const uint16_t request)
{
if (request == (request & permission))
*
* @return true if 'subject' is the wildcard, false if it is not.
*/
-static inline bool IsWildCardSubject(OicUuid_t *subject)
+INLINE_API bool IsWildCardSubject(OicUuid_t *subject)
{
if(NULL == subject)
{
* @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");
}
/**
- * 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;
}
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;
// 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;
}
{
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))
{
// 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);
#define TAG "SRM-PSI"
//SVR database buffer block size
+#ifdef _WIN32
+#define DB_FILE_SIZE_BLOCK 1023
+#else
const size_t DB_FILE_SIZE_BLOCK = 1023;
+#endif
/**
* Gets the Secure Virtual Database size
static const uint16_t CBOR_MAX_SIZE = 4400;
// PSTAT Map size - Number of mandatory items
-static const uint8_t PSTAT_MAP_SIZE = 7;
+static const uint8_t PSTAT_MAP_SIZE = 9;
static OicSecDpom_t gSm = SINGLE_SERVICE_CLIENT_DRIVEN;
static OicSecPstat_t gDefaultPstat =
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.");
return bRet;
}
+static bool ValidateQuery(const char * query)
+{
+ OIC_LOG (DEBUG, TAG, "In ValidateQuery");
+ if(NULL == gPstat)
+ {
+ return false;
+ }
+
+ bool bInterfaceQry = false; // does querystring contains 'if' query ?
+ bool bInterfaceMatch = false; // does 'if' query matches with oic.if.baseline ?
+
+ OicParseQueryIter_t parseIter = {.attrPos = NULL};
+
+ ParseQueryIterInit((unsigned char*)query, &parseIter);
+
+ while (GetNextQuery(&parseIter))
+ {
+ if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
+ {
+ bInterfaceQry = true;
+ if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
+ {
+ bInterfaceMatch = true;
+ }
+ }
+ }
+ return (bInterfaceQry ? bInterfaceMatch: true);
+}
/**
* The entity handler determines how to process a GET request.
*/
static OCEntityHandlerResult HandlePstatGetRequest (const OCEntityHandlerRequest * ehRequest)
{
+ OCEntityHandlerResult ehRet = OC_EH_OK;
+
OIC_LOG(INFO, TAG, "HandlePstatGetRequest processing GET request");
- // Convert ACL data into CBOR for transmission
+ //Checking if Get request is a query.
+ if (ehRequest->query)
+ {
+ OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
+ OIC_LOG(DEBUG, TAG, "HandlePstatGetRequest processing query");
+ if (!ValidateQuery(ehRequest->query))
+ {
+ ehRet = OC_EH_ERROR;
+ }
+ }
+
+ /*
+ * For GET or Valid Query request return doxm resource CBOR payload.
+ * For non-valid query return NULL json payload.
+ * A device will 'always' have a default Pstat, so PstatToCBORPayload will
+ * return valid pstat resource json.
+ */
size_t size = 0;
uint8_t *payload = NULL;
- OCStackResult res = PstatToCBORPayload(gPstat, &payload, &size);
-
- // A device should always have a default pstat. Therefore, payload should never be NULL.
- OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
+ if (ehRet == OC_EH_OK)
+ {
+ if(OC_STACK_OK != PstatToCBORPayload(gPstat, &payload, &size))
+ {
+ OIC_LOG(WARNING, TAG, "PstatToCBORPayload failed in HandlePstatGetRequest");
+ }
+ }
// Send response payload to request originator
if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, payload, size))
* resource or create a new resource.
* For pstat, it updates only tm and om.
*/
-static OCEntityHandlerResult HandlePstatPutRequest(const OCEntityHandlerRequest *ehRequest)
+static OCEntityHandlerResult HandlePstatPostRequest(const OCEntityHandlerRequest *ehRequest)
{
OCEntityHandlerResult ehRet = OC_EH_ERROR;
- OIC_LOG(INFO, TAG, "HandlePstatPutRequest processing PUT request");
+ OIC_LOG(INFO, TAG, "HandlePstatPostRequest processing POST request");
OicSecPstat_t *pstat = NULL;
if (ehRequest->payload)
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;
{
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)
{
if (IsAccessGranted(response) && gRequestHandler)
{
- return (gRequestHandler(endPoint, requestInfo));
+ gRequestHandler(endPoint, requestInfo);
+ return;
}
// Form a 'Error', 'slow response' or 'access deny' response and send to peer
void SRMDeInitPolicyEngine()
{
- return DeInitPolicyEngine(&g_policyEngineContext);
+ DeInitPolicyEngine(&g_policyEngineContext);
}
bool SRMIsSecurityResourceURI(const char* uri)
#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";
const char * OIC_JSON_OPTDATA_NAME = "optdata";
const char * OIC_JSON_SERVICE_DEVICE_ID = "svcdid";
const char * OIC_JSON_SERVICE_TYPE = "svct";
+const char* OIC_JSON_VALIDITY_NAME = "validity";
const char * OIC_JSON_PERIOD_NAME = "period";
const char * OIC_JSON_PERIODS_NAME = "prds";
const char * OIC_JSON_CRMS_NAME = "crms";
const char * OIC_JSON_RECURRENCES_NAME = "recurrence";
const char * OIC_JSON_SUPPORTED_CRED_TYPE_NAME = "sct";
-const char * OIC_JSON_DPC_NAME = "dpc";
+const char * OIC_JSON_DPC_NAME = "x.com.samsung.dpc";
const char * OIC_JSON_EDP_NAME = "edp";
const char * OIC_JSON_PIN_NAME = "pin";
const char * OIC_JSON_PDACL_NAME = "pdacl";
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";
do
{
- unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+ unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {0};
uint32_t outLen = 0;
B64Result b64Ret = B64_OK;
--- /dev/null
+/** @todo: Add Microsoft copyright */
+#include <stdio.h>
+#include <ctype.h>
+#include <time.h>
+#include <memory.h>
+#include <stdbool.h>
+
+#define TM_BASE_YEAR 1900
+
+static const int ydays[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
+
+bool is_leap_year(int yy)
+{
+ int yyyy = yy + TM_BASE_YEAR;
+
+ bool bLeap = false;
+ if (yyyy % 100 == 0)
+ {
+ return yyyy % 400 == 0;
+ }
+ return yyyy % 4 == 0;
+}
+
+
+char * strptime(const char *buf, const char *fmt, struct tm *tm)
+{
+ int temp = 0;
+ char c = '\0';
+
+ //check params
+ if ((fmt == NULL) || (tm == NULL))
+ {
+ return NULL;
+ }
+
+ //initialize the tm struct values
+ memset(tm, 0, sizeof(struct tm));
+ tm->tm_mday = 1;
+
+ while (buf && (c = *fmt++))
+ {
+ temp = 0;
+ if (c == '%')
+ {
+ switch (c = *fmt++)
+ {
+ case '%':
+ if (c != *buf++)
+ {
+ return NULL;
+ }
+ break;
+
+ case 'd': /* day of the month (1..31)*/
+ sscanf(buf, "%2d", &temp);
+ if (temp >= 1 && temp <= 31)
+ {
+ tm->tm_mday = temp;
+ buf += 2;
+ }
+ else
+ return NULL;
+ break;
+
+ case 'H': /* hour (0..23) */
+ sscanf(buf, "%2d", &temp);
+ if (temp >= 0 && temp <= 23)
+ {
+ tm->tm_hour = temp;
+ buf += 2;
+ }
+ else
+ return NULL;
+ break;
+
+ case 'M': /* minute (0..59) */
+ sscanf(buf, "%2d", &temp);
+ if (temp >= 0 && temp <= 59)
+ {
+ tm->tm_min = temp;
+ buf += 2;
+ }
+ else
+ return NULL;
+ break;
+
+ case 'm': /* month (1..12) */
+ sscanf(buf, "%2d", &temp);
+ if (temp >= 1 && temp <= 12)
+ {
+ tm->tm_mon = temp - 1;
+ buf += 2;
+ }
+ else
+ return NULL;
+ break;
+
+ case 'S': /* seconds (0..59) */
+ sscanf(buf, "%2d", &temp);
+ if (temp >= 0 && temp <= 59)
+ {
+ tm->tm_sec = temp;
+ buf += 2;
+ }
+ else
+ return NULL;
+ break;
+
+ case 'Y': /* year */
+ sscanf(buf, "%4d", &temp);
+ if (temp >= 0 && temp <= 9999)
+ {
+ tm->tm_year = temp - TM_BASE_YEAR;
+ buf += 4;
+ }
+ else
+ return NULL;
+ break;
+
+ default:
+ return NULL;
+ }
+ }
+ else
+ {
+ if (c != *buf++)
+ return NULL;
+ }
+ }
+
+ //calculate tm_wday and tm_yday
+ tm->tm_yday = ydays[tm->tm_mon] + ((is_leap_year(tm->tm_year) && (tm->tm_mon >= 2)) ? 1 : 0) + tm->tm_mday - 1;
+
+ //1st Jan 1900 was Monday, hence weekday = the number of days from 1/1/1900 modulus 7 + 1
+ tm->tm_wday = (365 * tm->tm_year) + (tm->tm_year / 4) + tm->tm_yday + 1; //1st Jan 1900 was Monday, hence add 1
+ if (is_leap_year(tm->tm_year))
+ tm->tm_wday--;
+ tm->tm_wday %= 7;
+
+ return (char*)buf;
+}
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);
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 };
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);
{
OCStackResult ret = OCCreateResource(&gSvcHandle,
OIC_RSRC_TYPE_SEC_SVC,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_SVC_URI,
SVCEntityHandler,
NULL,
{
OCStackResult ret = OCCreateResource(&gVerHandle,
OIC_RSRC_TYPE_SEC_VER,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_VER_URI,
VerEntityHandler,
NULL,
#include <stdlib.h>
#include <string.h>
+#include "utlist.h"
#include "cJSON.h"
#include "base64.h"
#include "cainterface.h"
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");
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;
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
VERIFY_NON_NULL(TAG, jsonObj, ERROR);
VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
- acl->resourcesLen = (size_t)cJSON_GetArraySize(jsonObj);
-
- VERIFY_SUCCESS(TAG, acl->resourcesLen > 0, ERROR);
- acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
- VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
+ size_t resourcesLen = (size_t)cJSON_GetArraySize(jsonObj);
+ VERIFY_SUCCESS(TAG, resourcesLen > 0, ERROR);
- size_t idxx = 0;
- do
+ for(size_t idxx = 0; idxx < resourcesLen; idxx++)
{
+ OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+ VERIFY_NON_NULL(TAG, rsrc, ERROR);
+
cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx);
VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);
+ //href
size_t jsonRsrcObjLen = 0;
cJSON *jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_HREF_NAME);
VERIFY_NON_NULL(TAG, jsonRsrcObj, ERROR);
VERIFY_SUCCESS(TAG, cJSON_String == jsonRsrcObj->type, ERROR);
jsonRsrcObjLen = strlen(jsonRsrcObj->valuestring) + 1;
- acl->resources[idxx] = (char*)OICMalloc(jsonRsrcObjLen);
+ rsrc->href = (char*)OICMalloc(jsonRsrcObjLen);
+ VERIFY_NON_NULL(TAG, (rsrc->href), ERROR);
+ OICStrcpy(rsrc->href, jsonRsrcObjLen, jsonRsrcObj->valuestring);
+
+ //rel
+ jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_REL_NAME);
+ if(jsonRsrcObj)
+ {
+ jsonRsrcObjLen = strlen(jsonRsrcObj->valuestring) + 1;
+ rsrc->rel = (char*)OICMalloc(jsonRsrcObjLen);
+ VERIFY_NON_NULL(TAG, (rsrc->rel), ERROR);
+ OICStrcpy(rsrc->rel, jsonRsrcObjLen, jsonRsrcObj->valuestring);
+ }
- VERIFY_NON_NULL(TAG, (acl->resources[idxx]), ERROR);
- OICStrcpy(acl->resources[idxx], jsonRsrcObjLen, jsonRsrcObj->valuestring);
+ //rt
+ jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_RT_NAME);
+ if(jsonRsrcObj && cJSON_Array == jsonRsrcObj->type)
+ {
+ rsrc->typeLen = (size_t)cJSON_GetArraySize(jsonRsrcObj);
+ VERIFY_SUCCESS(TAG, (0 < rsrc->typeLen), ERROR);
+ rsrc->types = (char**)OICCalloc(rsrc->typeLen, sizeof(char*));
+ VERIFY_NON_NULL(TAG, (rsrc->types), ERROR);
+ for(size_t i = 0; i < rsrc->typeLen; i++)
+ {
+ cJSON *jsonRsrcType = cJSON_GetArrayItem(jsonRsrcObj, i);
+ rsrc->types[i] = OICStrdup(jsonRsrcType->valuestring);
+ VERIFY_NON_NULL(TAG, (rsrc->types[i]), ERROR);
+ }
+ }
+
+ //if
+ jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_IF_NAME);
+ if(jsonRsrcObj && cJSON_Array == jsonRsrcObj->type)
+ {
+ rsrc->interfaceLen = (size_t)cJSON_GetArraySize(jsonRsrcObj);
+ VERIFY_SUCCESS(TAG, (0 < rsrc->interfaceLen), ERROR);
+ rsrc->interfaces = (char**)OICCalloc(rsrc->interfaceLen, sizeof(char*));
+ VERIFY_NON_NULL(TAG, (rsrc->interfaces), ERROR);
+ for(size_t i = 0; i < rsrc->interfaceLen; i++)
+ {
+ cJSON *jsonInterface = cJSON_GetArrayItem(jsonRsrcObj, i);
+ rsrc->interfaces[i] = OICStrdup(jsonInterface->valuestring);
+ VERIFY_NON_NULL(TAG, (rsrc->interfaces[i]), ERROR);
+ }
+ }
- } while ( ++idxx < acl->resourcesLen);
+ LL_APPEND(ace->resources, rsrc);
+ }
// Permissions -- Mandatory
jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_PERMISSION_NAME);
VERIFY_NON_NULL(TAG, jsonObj, ERROR);
VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
- acl->permission = jsonObj->valueint;
- //Period -- Not Mandatory
- cJSON *jsonPeriodObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_PERIOD_NAME);
- if(jsonPeriodObj)
+ ace->permission = jsonObj->valueint;
+
+ //Validity -- Not Mandatory
+ cJSON *jsonValidityObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_VALIDITY_NAME);
+ if(jsonValidityObj)
{
- VERIFY_SUCCESS(TAG, cJSON_Array == jsonPeriodObj->type, ERROR);
- acl->prdRecrLen = (size_t)cJSON_GetArraySize(jsonPeriodObj);
- if(acl->prdRecrLen > 0)
+ VERIFY_SUCCESS(TAG, cJSON_Array == jsonValidityObj->type, ERROR);
+ size_t validityLen = cJSON_GetArraySize(jsonValidityObj);
+ VERIFY_SUCCESS(TAG, (0 < validityLen), ERROR);
+
+ cJSON *jsonValidity = NULL;
+ for(size_t i = 0; i < validityLen; i++)
{
- acl->periods = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
- VERIFY_NON_NULL(TAG, acl->periods, ERROR);
+ jsonValidity = cJSON_GetArrayItem(jsonValidityObj, i);
+ VERIFY_NON_NULL(TAG, jsonValidity, ERROR);
+ VERIFY_SUCCESS(TAG, (jsonValidity->type == cJSON_Array), ERROR);
+
+ OicSecValidity_t* validity = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+ VERIFY_NON_NULL(TAG, validity, ERROR);
+ LL_APPEND(ace->validities, validity);
- cJSON *jsonPeriod = NULL;
- for(size_t i = 0; i < acl->prdRecrLen; i++)
+ //Period
+ cJSON* jsonPeriod = cJSON_GetArrayItem(jsonValidity, 0);
+ if(jsonPeriod)
{
- jsonPeriod = cJSON_GetArrayItem(jsonPeriodObj, i);
- VERIFY_NON_NULL(TAG, jsonPeriod, ERROR);
+ VERIFY_SUCCESS(TAG, (cJSON_String == jsonPeriod->type), ERROR);
jsonObjLen = strlen(jsonPeriod->valuestring) + 1;
- acl->periods[i] = (char*)OICMalloc(jsonObjLen);
- VERIFY_NON_NULL(TAG, acl->periods[i], ERROR);
- OICStrcpy(acl->periods[i], jsonObjLen, jsonPeriod->valuestring);
+ validity->period = (char*)OICMalloc(jsonObjLen);
+ VERIFY_NON_NULL(TAG, validity->period, ERROR);
+ OICStrcpy(validity->period, jsonObjLen, jsonPeriod->valuestring);
}
- }
- }
- //Recurrence -- Not mandatory
- cJSON *jsonRecurObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_RECURRENCES_NAME);
- if(jsonRecurObj)
- {
-
- VERIFY_SUCCESS(TAG, cJSON_Array == jsonRecurObj->type, ERROR);
- if(acl->prdRecrLen > 0)
- {
- acl->recurrences = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
- VERIFY_NON_NULL(TAG, acl->recurrences, ERROR);
-
- cJSON *jsonRecur = NULL;
- for(size_t i = 0; i < acl->prdRecrLen; i++)
+ //Recurrence
+ cJSON* jsonRecurObj = cJSON_GetArrayItem(jsonValidity, 1);
+ if(jsonRecurObj)
{
- jsonRecur = cJSON_GetArrayItem(jsonRecurObj, i);
- VERIFY_NON_NULL(TAG, jsonRecur, ERROR);
- jsonObjLen = strlen(jsonRecur->valuestring) + 1;
- acl->recurrences[i] = (char*)OICMalloc(jsonObjLen);
- VERIFY_NON_NULL(TAG, acl->recurrences[i], ERROR);
- OICStrcpy(acl->recurrences[i], jsonObjLen, jsonRecur->valuestring);
+ VERIFY_SUCCESS(TAG, (cJSON_Array == jsonRecurObj->type), ERROR);
+ validity->recurrenceLen = cJSON_GetArraySize(jsonRecurObj);
+ VERIFY_SUCCESS(TAG, (0 < validity->recurrenceLen), ERROR);
+
+ validity->recurrences = (char**)OICCalloc(validity->recurrenceLen, sizeof(char*));
+ VERIFY_NON_NULL(TAG, validity->recurrences, ERROR);
+
+ cJSON *jsonRecur = NULL;
+ for(size_t i = 0; i < validity->recurrenceLen; i++)
+ {
+ jsonRecur = cJSON_GetArrayItem(jsonRecurObj, i);
+ VERIFY_NON_NULL(TAG, jsonRecur, ERROR);
+ jsonObjLen = strlen(jsonRecur->valuestring) + 1;
+ validity->recurrences[i] = (char*)OICMalloc(jsonObjLen);
+ VERIFY_NON_NULL(TAG, validity->recurrences[i], ERROR);
+ OICStrcpy(validity->recurrences[i], jsonObjLen, jsonRecur->valuestring);
+ }
}
}
}
-
- acl->next = NULL;
-
} while( ++idx < numAcl);
}
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);
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.
srmtest_env = env.Clone()
src_dir = srmtest_env.get('SRC_DIR')
+target_os = env.get('TARGET_OS')
######################################################################
# Build flags
######################################################################
srmtest_env.PrependUnique(CPPPATH = [
- '../../ocmalloc/include',
+ '../../../c_common/oic_malloc/include',
'../../connectivity/inc',
'../../connectivity/api',
'../../connectivity/external/inc',
'../../connectivity/lib/libcoap-4.1.1',
- '../include',
'../include/internal',
'../../logger/include',
- '../../ocmalloc/include',
'../../stack/include',
'../../stack/include/internal',
'../../../oc_logger/include',
'../../../../extlibs/gtest/gtest-1.7.0/include',
'../../../../extlibs/cjson/',
- '../provisioning/include',
-# '../../../../extlibs/tinydtls/',
+ '../provisioning/include',
'../include'
])
'gtest_main'])
if env.get('SECURED') == '1':
- srmtest_env.AppendUnique(LIBS = ['tinydtls'])
+ srmtest_env.AppendUnique(LIBS = ['tinydtls', 'timer'])
-if not env.get('RELEASE'):
+if env.get('LOGGING') == '1':
srmtest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+if target_os == 'windows':
+ srmtest_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE'])
+ srmtest_env.AppendUnique(LIBS = ['advapi32', 'kernel32', 'ws2_32', 'iphlpapi'])
+else:
+ # TODO: Implement feature check.
+ srmtest_env.AppendUnique(CPPDEFINES = ['HAVE_LOCALTIME_R'])
+
######################################################################
# Source files and Targets
######################################################################
'base64tests.cpp',
'svcresourcetest.cpp',
'srmtestcommon.cpp',
- 'directpairingtest.cpp'])
+ 'directpairingtest.cpp',
+ 'crlresourcetest.cpp'])
Alias("test", [unittest])
unittest_src_dir = src_dir + '/resource/csdk/security/unittest/'
-unittest_build_dir = env.get('BUILD_DIR') + 'resource/csdk/security/unittest'
+unittest_build_dir = os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk', 'security', 'unittest') + os.sep
-srmtest_env.AppendUnique(CPPDEFINES = ['SECURITY_BUILD_UNITTEST_DIR='+unittest_build_dir])
+srmtest_env.AppendUnique(CPPDEFINES = ['SECURITY_BUILD_UNITTEST_DIR='+unittest_build_dir.encode('string_escape')])
srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
unittest_src_dir + 'oic_unittest.json'))
unittest_src_dir + 'oic_unittest_acl1.json'))
srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
unittest_src_dir + 'oic_unittest_default_acl.json'))
+srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
+ unittest_src_dir + 'oic_svr_db.json'))
srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
unittest_src_dir + 'oic_unittest.dat'))
unittest_src_dir + 'oic_unittest_acl1.dat'))
srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
unittest_src_dir + 'oic_unittest_default_acl.dat'))
-
+srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
+ unittest_src_dir + 'oic_svr_db_prov.dat'))
+srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
+ unittest_src_dir + 'oic_svr_db.dat'))
+
env.AppendTarget('test')
if env.get('TEST') == '1':
target_os = env.get('TARGET_OS')
- if target_os == 'linux':
+ if target_os in ['linux', 'windows']:
out_dir = env.get('BUILD_DIR')
result_dir = env.get('BUILD_DIR') + '/test_out/'
if not os.path.isdir(result_dir):
os.makedirs(result_dir)
srmtest_env.AppendENVPath('GTEST_OUTPUT', ['xml:'+ result_dir])
srmtest_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir])
+ srmtest_env.AppendENVPath('PATH', [os.path.join(out_dir, 'resource', 'csdk')])
srmtest_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
ut = srmtest_env.Command ('ut', None, out_dir + '/resource/csdk/security/unittest/unittest')
AlwaysBuild ('ut')
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "gtest/gtest.h"
-#include <pwd.h>
-#include <grp.h>
-#include <linux/limits.h>
+#include "utlist.h"
#include <sys/stat.h>
#include "ocstack.h"
#include "psinterface.h"
#define TAG "SRM-ACL-UT"
// These paths match jenkins build configuration.
-const char* DEFAULT_ACL_FILE_NAME = "/oic_unittest_default_acl.dat";
-const char* ACL1_FILE_NAME = "/oic_unittest_acl1.dat";
+const char* DEFAULT_ACL_FILE_NAME = "oic_unittest_default_acl.dat";
+const char* ACL1_FILE_NAME = "oic_unittest_acl1.dat";
#define NUM_ACE_FOR_WILDCARD_IN_ACL1_DAT (1)
-TEST(ACLResourceTest, CBORDefaultACLConversion)
+static bool AddResourceToACE(OicSecAce_t* ace, const char* rsrcName,
+ const char* typeName, const char* interfaceName)
{
- OicSecAcl_t *defaultAcl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
- ASSERT_TRUE(defaultAcl != NULL);
- uint8_t defaultAclSub[] = { 0x2a };
- memcpy(defaultAcl->subject.id, defaultAclSub, sizeof(defaultAclSub));
- defaultAcl->permission = 2;
- const char *defaulAclRsrc[] = { "/oic/res", "/oic/d", "/oic/p", "/oic/res/types/d",
- "/oic/ad", "/oic/sec/acl", "/oic/sec/doxm", "/oic/sec/pstat"};
- defaultAcl->resourcesLen = 8;
- defaultAcl->resources = (char **)OICCalloc(defaultAcl->resourcesLen, sizeof(char *));
- ASSERT_TRUE(defaultAcl->resources != NULL);
- for (size_t i = 0 ; i < defaultAcl->resourcesLen; i++)
+ OicSecRsrc_t* rsrc = NULL;
+
+ VERIFY_NON_NULL(TAG, ace, ERROR);
+ VERIFY_NON_NULL(TAG, rsrcName, ERROR);
+ VERIFY_NON_NULL(TAG, interfaceName, ERROR);
+ VERIFY_NON_NULL(TAG, typeName, ERROR);
+
+ rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+ VERIFY_NON_NULL(TAG, rsrc, ERROR);
+ rsrc->href = OICStrdup(rsrcName);
+ VERIFY_NON_NULL(TAG, rsrc->href, ERROR);
+
+ rsrc->typeLen = 1;
+ rsrc->types = (char**)OICCalloc(1, sizeof(char*));
+ VERIFY_NON_NULL(TAG, rsrc->types, ERROR);
+ rsrc->types[0] = OICStrdup(typeName);
+ VERIFY_NON_NULL(TAG, rsrc->types[0], ERROR);
+
+ rsrc->interfaceLen = 1;
+ rsrc->interfaces = (char**)OICCalloc(1, sizeof(char*));
+ VERIFY_NON_NULL(TAG, rsrc->interfaces, ERROR);
+ rsrc->interfaces[0] = OICStrdup(interfaceName);
+ VERIFY_NON_NULL(TAG, rsrc->interfaces[0], ERROR);
+
+ LL_APPEND(ace->resources, rsrc);
+ return true;
+exit:
+ if(rsrc)
+ {
+ if(rsrc->href)
+ {
+ OICFree(rsrc->href);
+ OICFree(rsrc->types[0]);
+ OICFree(rsrc->types);
+ OICFree(rsrc->interfaces[0]);
+ OICFree(rsrc->interfaces);
+ }
+ OICFree(rsrc);
+ }
+ return false;
+}
+
+static int GetNumberOfResource(const OicSecAce_t* ace)
+{
+ int ret = 0;
+ OicSecRsrc_t* rsrc = NULL;
+ LL_FOREACH(ace->resources, rsrc)
{
- defaultAcl->resources[i] = OICStrdup(defaulAclRsrc[i]);
- ASSERT_TRUE(defaultAcl->resources[i] != NULL);
+ ret++;
}
+
+ return ret;
+}
+
+TEST(ACLResourceTest, CBORDefaultACLConversion)
+{
+ uint8_t defaultAclSub[] = { 0x2a };
uint8_t defaultAclOwnrs[] = {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32};
+
+ OicSecAcl_t *defaultAcl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+ ASSERT_TRUE(NULL != defaultAcl);
+ OicSecAce_t *ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+ ASSERT_TRUE(NULL != ace);
+ ace->permission = 2;
+ memcpy(ace->subjectuuid.id, defaultAclSub, sizeof(defaultAclSub));
+ LL_APPEND(defaultAcl->aces, ace);
+
+ EXPECT_EQ(true, AddResourceToACE(ace, "/oic/res", "oic.wk.res", "oic.if.ll"));
+ EXPECT_EQ(true, AddResourceToACE(ace, "/oic/d", "oic.wk.d", "oic.if.r"));
+ EXPECT_EQ(true, AddResourceToACE(ace, "/oic/p", "oic.wk.p", "oic.if.r"));
+ EXPECT_EQ(true, AddResourceToACE(ace, "/oic/res/types/d", "oic.wk.unknow", "oic.if.r"));
+ EXPECT_EQ(true, AddResourceToACE(ace, "/oic/ad", "oic.wk.ad", "oic.if.baseline"));
+ EXPECT_EQ(true, AddResourceToACE(ace, "/oic/sec/acl", "oic.r.acl", "oic.if.baseline"));
+ EXPECT_EQ(true, AddResourceToACE(ace, "/oic/sec/doxm", "oic.r.doxm" ,"oic.if.baseline"));
+ EXPECT_EQ(true, AddResourceToACE(ace, "/oic/sec/pstat", "oic.r.pstat" ,"oic.if.baseline"));
+
memcpy(defaultAcl->rownerID.id, defaultAclOwnrs, sizeof(defaultAclOwnrs));
size_t defaultAclSize = 0;
uint8_t *defaultPsStorage = NULL;
OCStackResult convRet = AclToCBORPayload(defaultAcl, &defaultPsStorage, &defaultAclSize);
EXPECT_EQ(OC_STACK_OK, convRet);
- ASSERT_TRUE(defaultPsStorage != NULL);
+ ASSERT_TRUE(NULL != defaultPsStorage);
EXPECT_NE(0, defaultAclSize);
OicSecAcl_t* convertedAcl = CBORPayloadToAcl(defaultPsStorage, defaultAclSize);
- ASSERT_TRUE(convertedAcl != NULL);
+ ASSERT_TRUE(NULL != convertedAcl);
- EXPECT_EQ(defaultAcl->resourcesLen, convertedAcl->resourcesLen);
- for(int i = 0; i < convertedAcl->resourcesLen; i++)
+ size_t rsrcCnt1 = 0;
+ size_t rsrcCnt2 = 0;
+ OicSecAce_t* tempAce = NULL;
+ LL_FOREACH(defaultAcl->aces, tempAce)
+ {
+ rsrcCnt1 += GetNumberOfResource(tempAce);
+ }
+ tempAce = NULL;
+ LL_FOREACH(convertedAcl->aces, tempAce)
{
- EXPECT_EQ(0, strcmp(defaultAcl->resources[i], convertedAcl->resources[i]));
+ rsrcCnt2 += GetNumberOfResource(tempAce);
}
+ EXPECT_EQ(rsrcCnt1, rsrcCnt2);
DeleteACLList(convertedAcl);
DeleteACLList(defaultAcl);
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;
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
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);
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;
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
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)
{
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);
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));
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;
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);
// 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();
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));
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;
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);
// 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);
//'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));
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;
//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);
#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");
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);
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);
}
}
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);
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)
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);
}
{
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);
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);
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;
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));
+}
--- /dev/null
+/******************************************************************
+*
+* 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
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));
}
}
}
+#ifndef HAVE_LOCALTIME_R
+
+#define localtime_r localtime_r_compat
+
+/**
+ * @description An implementation of `localtime_r` for systems which only
+ * have a `localtime` implementation.
+ */
+static tm* localtime_r_compat(const time_t* timer, tm* result)
+{
+ if (NULL == result)
+ {
+ OIC_LOG(ERROR, TAG, "localtime_r received null results parameter");
+ }
+
+ if (NULL == timer)
+ {
+ OIC_LOG(WARNING, TAG, "localtime_r received null timer parameter");
+ }
+
+ tm* tempPtr = localtime(timer);
+ memcpy(result, tempPtr, sizeof(tm));
+ return result;
+}
+#endif
static void checkValidityOfRequest(char *recurStr, char *periodStr,int startTime, int endTime,
int byDay)
{
"href": "/oic/res",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.res"],
+ "if": ["oic.if.ll"]
},
{
"href": "/oic/d",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.d"],
+ "if": ["oic.if.baseline", "oic.if.r"]
},
{
"href": "/oic/p",
"rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/res/types/d",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/ad",
- "rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
}
],
"permission": 2
{
"href": "/oic/sec/doxm",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.doxm"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/pstat",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.pstat"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/acl",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.acl"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 6
{
"href": "/oic/sec/pconf",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.pconf"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/dpairing",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.dpairing"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 6
"deviceuuid": "756E6B6E-6F77-6564-4465-766963654964",
"devowneruuid": "",
"rowneruuid": "756E6B6E-6F77-6564-4465-766963654964",
- "dpc": true
+ "x.com.samsung.dpc": true
}
}
\ No newline at end of file
{
"href": "/oic/light",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/fan",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
}
],
- "permission": 31
+ "permission": 31
},
{
"subjectuuid": "33333333-3333-3333-3333-333333333333",
{
"href": "/oic/light",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/garage",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
}
],
- "permission": 31
+ "permission": 31
}
]
},
-¿caclY\ 2\8b¢faclist¡daces\84£ksubjectuuida*iresources\86¤dhrefh/oic/rescrel`brt`bif`¤dhreff/oic/dcrel`brt`bif`¤dhreff/oic/pcrel`brt`bif`¤dhrefp/oic/res/types/dcrel`brt`bif`¤dhrefg/oic/adcrel`brt`bif`¤dhrefl/oic/sec/aclcrel`brt`bif`jpermission\ 2£ksubjectuuida*iresources\82¤dhrefm/oic/sec/doxmcrel`brt`bif`¤dhrefn/oic/sec/pstatcrel`brt`bif`jpermission\ 6£ksubjectuuidx$31313131-3131-3131-3131-313131313131iresources\82¤dhrefj/oic/lightcrel`brt`bif`¤dhrefh/oic/fancrel`brt`bif`jpermission\18\1f£ksubjectuuidx$33333333-3333-3333-3333-333333333333iresources\82¤dhrefj/oic/lightcrel`brt`bif`¤dhrefk/oic/garagecrel`brt`bif`jpermission\18\1fjrowneruuidx$32323232-3232-3232-3232-323232323232ÿ
\ No newline at end of file
+¿caclY\ 3 ¢faclist¡daces\84£ksubjectuuida*iresources\83¤dhrefh/oic/resbrt\81joic.wk.resbif\81ioic.if.llcrel`¤dhreff/oic/dbrt\81hoic.wk.dbif\82ooic.if.baselinehoic.if.rcrel`¤dhreff/oic/pbrt\81hoic.wk.pbif\82ooic.if.baselinehoic.if.rcrel`jpermission\ 2£ksubjectuuida*iresources\82¤dhrefm/oic/sec/doxmbrt\81joic.r.doxmbif\81ooic.if.baselinecrel`¤dhrefn/oic/sec/pstatbrt\81koic.r.pstatbif\81ooic.if.baselinecrel`jpermission\ 6£ksubjectuuidx$31313131-3131-3131-3131-313131313131iresources\82¤dhrefj/oic/lightbrt\81hoic.corebif\81ooic.if.baselinecrel`¤dhrefh/oic/fanbrt\81hoic.corebif\81ooic.if.baselinecrel`jpermission\18\1f£ksubjectuuidx$33333333-3333-3333-3333-333333333333iresources\82¤dhrefj/oic/lightbrt\81hoic.corebif\81ooic.if.baselinecrel`¤dhrefk/oic/garagebrt\81hoic.corebif\81ooic.if.baselinecrel`jpermission\18\1fjrowneruuidx$32323232-3232-3232-3232-323232323232ÿ
\ No newline at end of file
{
"href": "/oic/res",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.res"],
+ "if": ["oic.if.ll"]
},
{
"href": "/oic/d",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.d"],
+ "if": ["oic.if.baseline", "oic.if.r"]
},
{
"href": "/oic/p",
"rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/res/types/d",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/ad",
- "rel": "",
- "rt": "",
- "if": ""
- },
- {
- "href": "/oic/sec/acl",
- "rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
}
],
"permission": 2
{
"href": "/oic/sec/doxm",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.doxm"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/sec/pstat",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.r.pstat"],
+ "if": ["oic.if.baseline"]
}
],
"permission": 6
{
"href": "/oic/light",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/fan",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
}
],
- "permission": 31
+ "permission": 31
},
{
"subjectuuid": "33333333-3333-3333-3333-333333333333",
{
"href": "/oic/light",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
},
{
"href": "/oic/garage",
"rel": "",
- "rt": "",
- "if": ""
+ "rt": ["oic.core"],
+ "if": ["oic.if.baseline"]
}
],
- "permission": 31
+ "permission": 31
}
]
},
-¿caclY\ 1X¢faclist¡daces\81£ksubjectuuida*iresources\88¤dhrefh/oic/rescrel`brt`bif`¤dhreff/oic/dcrel`brt`bif`¤dhreff/oic/pcrel`brt`bif`¤dhrefp/oic/res/types/dcrel`brt`bif`¤dhrefg/oic/adcrel`brt`bif`¤dhrefl/oic/sec/aclcrel`brt`bif`¤dhrefm/oic/sec/doxmcrel`brt`bif`¤dhrefn/oic/sec/pstatcrel`brt`bif`jpermission\ 2jrowneruuidx$32323232-3232-3232-3232-323232323232ÿ
\ No newline at end of file
+¿caclY\ 1âfaclist¡daces\81£ksubjectuuida*iresources\86¤dhrefh/oic/resbrt\81joic.wk.resbif\81ioic.if.llcrel`¤dhreff/oic/dbrt\81hoic.wk.dbif\82ooic.if.baselinehoic.if.rcrel`¤dhreff/oic/pbrt\81hoic.wk.pbif\82ooic.if.baselinehoic.if.rcrel`¤dhrefm/oic/sec/doxmbrt\81joic.r.doxmbif\81ooic.if.baselinecrel`¤dhrefn/oic/sec/pstatbrt\81koic.r.pstatbif\81ooic.if.baselinecrel`¤dhrefl/oic/sec/aclbrt\81ioic.r.aclbif\81ooic.if.baselinecrel`jpermission\ 2jrowneruuidx$32323232-3232-3232-3232-323232323232ÿ
\ No newline at end of file
{
"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
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "gtest/gtest.h"
-#include <pwd.h>
-#include <grp.h>
-#include <linux/limits.h>
#include "ocstack.h"
#include "cainterface.h"
#include "srmresourcestrings.h"
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
#include "gtest/gtest.h"
#include "ocpayload.h"
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "gtest/gtest.h"
+#ifdef HAVE_PWD_H
#include <pwd.h>
+#endif
+#ifdef HAVE_GRP_H
#include <grp.h>
+#endif
+#ifdef HAVE_LINUX_LIMITS_H
#include <linux/limits.h>
+#endif
#include "ocstack.h"
#include "cainterface.h"
#include "secureresourcemanager.h"
EXPECT_TRUE(&gpsi == ps);
}
+#if !(defined(HAVE_LINUX_LIMITS_H) && defined(HAVE_PWD_H))
+TEST(PersistentStorageHandlerTest, DISABLED_PersistentStorageValidHandlers)
+{
+ /** @todo: Implement test on non-Linux platform */
+}
+#else
TEST(PersistentStorageHandlerTest, PersistentStorageValidHandlers)
{
OCPersistentStorage *psi = SRMGetPersistentStorageHandler();
}
psi->unlink(outFilePath);
}
+#endif
+
#define STRINGIZE(x) STRINGIZE2(x)
// TODO: Remove this, once all cbor related are completed.
-char* ReadFile(const char* filename)
+char* ReadFileToBuffer(const char* filename)
{
FILE *fp = NULL;
#ifndef IOTVT_SRM_TEST_COMMON_H
#define IOTVT_SRM_TEST_COMMON_H
-char* ReadFile(const char* filename);
+char* ReadFileToBuffer(const char* filename);
bool ReadCBORFile(const char* filename, const char* rsrcName, uint8_t **payload, size_t *size);
void SetPersistentHandler(OCPersistentStorage *ps, bool set);
extern "C"
{
#endif
-OCStackResult OCParsePayload(OCPayload** outPayload, OCPayloadType type,
+OC_EXPORT_TEST OCStackResult OCParsePayload(OCPayload** outPayload, OCPayloadType type,
const uint8_t* payload, size_t payloadSize);
-OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t* size);
+OC_EXPORT_TEST OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t* size);
#ifdef __cplusplus
}
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
/** The coap scheme */
#define OC_COAP_SCHEME "coap://"
-/** the first outgoing sequence number will be 5*/
-#define OC_OFFSET_SEQUENCE_NUMBER (4)
+/** the first outgoing sequence number will be 2*/
+#define OC_OFFSET_SEQUENCE_NUMBER (1)
/**
* This structure will be created in occoap and passed up the stack on the server side.
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.
OCResourceProperty resourceProperties, uint8_t enable);
#endif
-const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
+OC_EXPORT const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
-OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
+OC_EXPORT OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out);
typedef struct OCResource OCResource;
-void OCPayloadDestroy(OCPayload* payload);
+OC_EXPORT void OCPayloadDestroy(OCPayload* payload);
// Representation Payload
-OCRepPayload* OCRepPayloadCreate();
+OC_EXPORT OCRepPayload* OCRepPayloadCreate();
-size_t calcDimTotal(const size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+OC_EXPORT size_t calcDimTotal(const size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-OCRepPayload* OCRepPayloadClone(const OCRepPayload* payload);
+OC_EXPORT OCRepPayload* OCRepPayloadClone(const OCRepPayload* payload);
-void OCRepPayloadAppend(OCRepPayload* parent, OCRepPayload* child);
+OC_EXPORT void OCRepPayloadAppend(OCRepPayload* parent, OCRepPayload* child);
-bool OCRepPayloadSetUri(OCRepPayload* payload, const char* uri);
+OC_EXPORT bool OCRepPayloadSetUri(OCRepPayload* payload, const char* uri);
-bool OCRepPayloadAddResourceType(OCRepPayload* payload, const char* resourceType);
-bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* interface);
+OC_EXPORT bool OCRepPayloadAddResourceType(OCRepPayload* payload, const char* resourceType);
+OC_EXPORT bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* iface);
+OC_EXPORT bool OCRepPayloadAddModelVersion(OCRepPayload* payload, const char* dmv);
-bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceType);
-bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface);
+OC_EXPORT bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceType);
+OC_EXPORT bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* iface);
-bool OCRepPayloadIsNull(const OCRepPayload* payload, const char* name);
-bool OCRepPayloadSetNull(OCRepPayload* payload, const char* name);
+OC_EXPORT bool OCRepPayloadIsNull(const OCRepPayload* payload, const char* name);
+OC_EXPORT bool OCRepPayloadSetNull(OCRepPayload* payload, const char* name);
-bool OCRepPayloadSetPropInt(OCRepPayload* payload, const char* name, int64_t value);
-bool OCRepPayloadGetPropInt(const OCRepPayload* payload, const char* name, int64_t* value);
+OC_EXPORT bool OCRepPayloadSetPropInt(OCRepPayload* payload, const char* name, int64_t value);
+OC_EXPORT bool OCRepPayloadGetPropInt(const OCRepPayload* payload, const char* name, int64_t* value);
-bool OCRepPayloadSetPropDouble(OCRepPayload* payload, const char* name, double value);
-bool OCRepPayloadGetPropDouble(const OCRepPayload* payload, const char* name, double* value);
+OC_EXPORT bool OCRepPayloadSetPropDouble(OCRepPayload* payload, const char* name, double value);
+OC_EXPORT bool OCRepPayloadGetPropDouble(const OCRepPayload* payload, const char* name, double* value);
/**
* This function allocates memory for the byte string and sets it in the payload.
*
* @return true on success, false upon failure.
*/
-bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCByteString value);
+OC_EXPORT bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCByteString value);
/**
* This function sets the byte string in the payload.
*
* @return true on success, false upon failure.
*/
-bool OCRepPayloadSetPropByteStringAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetPropByteStringAsOwner(OCRepPayload* payload, const char* name,
OCByteString* value);
/**
*
* @return true on success, false upon failure.
*/
-bool OCRepPayloadGetPropByteString(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetPropByteString(const OCRepPayload* payload, const char* name,
OCByteString* value);
-bool OCRepPayloadSetPropString(OCRepPayload* payload, const char* name, const char* value);
-bool OCRepPayloadSetPropStringAsOwner(OCRepPayload* payload, const char* name, char* value);
-bool OCRepPayloadGetPropString(const OCRepPayload* payload, const char* name, char** value);
+OC_EXPORT bool OCRepPayloadSetPropString(OCRepPayload* payload, const char* name, const char* value);
+OC_EXPORT bool OCRepPayloadSetPropStringAsOwner(OCRepPayload* payload, const char* name, char* value);
+OC_EXPORT bool OCRepPayloadGetPropString(const OCRepPayload* payload, const char* name, char** value);
-bool OCRepPayloadSetPropBool(OCRepPayload* payload, const char* name, bool value);
-bool OCRepPayloadGetPropBool(const OCRepPayload* payload, const char* name, bool* value);
+OC_EXPORT bool OCRepPayloadSetPropBool(OCRepPayload* payload, const char* name, bool value);
+OC_EXPORT bool OCRepPayloadGetPropBool(const OCRepPayload* payload, const char* name, bool* value);
-bool OCRepPayloadSetPropObject(OCRepPayload* payload, const char* name, const OCRepPayload* value);
-bool OCRepPayloadSetPropObjectAsOwner(OCRepPayload* payload, const char* name,
- OCRepPayload* value);
-bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OCRepPayload** value);
+OC_EXPORT bool OCRepPayloadSetPropObject(OCRepPayload* payload, const char* name, const OCRepPayload* value);
+OC_EXPORT bool OCRepPayloadSetPropObjectAsOwner(OCRepPayload* payload, const char* name, OCRepPayload* value);
+OC_EXPORT bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OCRepPayload** value);
/**
* This function allocates memory for the byte string array and sets it in the payload.
*
* @return true on success, false upon failure.
*/
-bool OCRepPayloadSetByteStringArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetByteStringArrayAsOwner(OCRepPayload* payload, const char* name,
OCByteString* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
/**
*
* @return true on success, false upon failure.
*/
-bool OCRepPayloadSetByteStringArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetByteStringArray(OCRepPayload* payload, const char* name,
const OCByteString* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
/**
*
* @return true on success, false upon failure.
*/
-bool OCRepPayloadGetByteStringArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetByteStringArray(const OCRepPayload* payload, const char* name,
OCByteString** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetIntArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetIntArrayAsOwner(OCRepPayload* payload, const char* name,
int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetIntArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetIntArray(OCRepPayload* payload, const char* name,
const int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetIntArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetIntArray(const OCRepPayload* payload, const char* name,
int64_t** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetDoubleArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetDoubleArrayAsOwner(OCRepPayload* payload, const char* name,
double* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetDoubleArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetDoubleArray(OCRepPayload* payload, const char* name,
const double* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetDoubleArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetDoubleArray(const OCRepPayload* payload, const char* name,
double** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetStringArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetStringArrayAsOwner(OCRepPayload* payload, const char* name,
char** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetStringArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetStringArray(OCRepPayload* payload, const char* name,
const char** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetStringArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetStringArray(const OCRepPayload* payload, const char* name,
char*** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetBoolArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetBoolArrayAsOwner(OCRepPayload* payload, const char* name,
bool* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetBoolArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetBoolArray(OCRepPayload* payload, const char* name,
const bool* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetBoolArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetBoolArray(const OCRepPayload* payload, const char* name,
bool** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetPropObjectArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetPropObjectArrayAsOwner(OCRepPayload* payload, const char* name,
OCRepPayload** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetPropObjectArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetPropObjectArray(OCRepPayload* payload, const char* name,
const OCRepPayload** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetPropObjectArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetPropObjectArray(const OCRepPayload* payload, const char* name,
OCRepPayload*** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-void OCRepPayloadDestroy(OCRepPayload* payload);
+OC_EXPORT void OCRepPayloadDestroy(OCRepPayload* payload);
// Discovery Payload
-OCDiscoveryPayload* OCDiscoveryPayloadCreate();
+OC_EXPORT OCDiscoveryPayload* OCDiscoveryPayloadCreate();
-OCSecurityPayload* OCSecurityPayloadCreate(const uint8_t* securityData, size_t size);
-void OCSecurityPayloadDestroy(OCSecurityPayload* payload);
+OC_EXPORT OCSecurityPayload* OCSecurityPayloadCreate(const uint8_t* securityData, size_t size);
+OC_EXPORT void OCSecurityPayloadDestroy(OCSecurityPayload* payload);
-void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
- uint16_t securePort, uint16_t tcpPort);
-void OCDiscoveryPayloadAddNewResource(OCDiscoveryPayload* payload, OCResourcePayload* res);
-bool OCResourcePayloadAddStringLL(OCStringLL **payload, const char* type);
+#ifndef TCP_ADAPTER
+OC_EXPORT void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
+ uint16_t securePort);
+#else
+OC_EXPORT void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
+ uint16_t securePort, uint16_t tcpPort);
+#endif
+OC_EXPORT void OCDiscoveryPayloadAddNewResource(OCDiscoveryPayload* payload, OCResourcePayload* res);
+OC_EXPORT bool OCResourcePayloadAddStringLL(OCStringLL **payload, const char* type);
-size_t OCDiscoveryPayloadGetResourceCount(OCDiscoveryPayload* payload);
-OCResourcePayload* OCDiscoveryPayloadGetResource(OCDiscoveryPayload* payload, size_t index);
+OC_EXPORT size_t OCDiscoveryPayloadGetResourceCount(OCDiscoveryPayload* payload);
+OC_EXPORT OCResourcePayload* OCDiscoveryPayloadGetResource(OCDiscoveryPayload* payload, size_t index);
-void OCDiscoveryResourceDestroy(OCResourcePayload* payload);
-void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload);
+OC_EXPORT void OCDiscoveryResourceDestroy(OCResourcePayload* payload);
+OC_EXPORT void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload);
// Device Payload
-OCDevicePayload* OCDevicePayloadCreate(const char* sid, const char* dname,
+OC_EXPORT OCDevicePayload* OCDevicePayloadCreate(const char* sid, const char* dname,
const OCStringLL *types, const char* specVer, const char* dmVer);
-void OCDevicePayloadDestroy(OCDevicePayload* payload);
+OC_EXPORT void OCDevicePayloadDestroy(OCDevicePayload* payload);
// Platform Payload
-OCPlatformPayload* OCPlatformPayloadCreate(const OCPlatformInfo* platformInfo);
-OCPlatformPayload* OCPlatformPayloadCreateAsOwner(OCPlatformInfo* platformInfo);
-void OCPlatformInfoDestroy(OCPlatformInfo *info);
-void OCPlatformPayloadDestroy(OCPlatformPayload* payload);
+OC_EXPORT OCPlatformPayload* OCPlatformPayloadCreate(const OCPlatformInfo* platformInfo);
+OC_EXPORT OCPlatformPayload* OCPlatformPayloadCreateAsOwner(OCPlatformInfo* platformInfo);
+OC_EXPORT void OCPlatformInfoDestroy(OCPlatformInfo *info);
+OC_EXPORT void OCPlatformPayloadDestroy(OCPlatformPayload* payload);
// Presence Payload
-OCPresencePayload* OCPresencePayloadCreate(uint32_t seqNum, uint32_t maxAge,
+OC_EXPORT OCPresencePayload* OCPresencePayloadCreate(uint32_t seqNum, uint32_t maxAge,
OCPresenceTrigger trigger, const char* resourceType);
-void OCPresencePayloadDestroy(OCPresencePayload* payload);
+OC_EXPORT void OCPresencePayloadDestroy(OCPresencePayload* payload);
// Helper API
-OCStringLL* CloneOCStringLL (OCStringLL* ll);
-void OCFreeOCStringLL(OCStringLL* ll);
+OC_EXPORT OCStringLL* CloneOCStringLL (OCStringLL* ll);
+OC_EXPORT void OCFreeOCStringLL(OCStringLL* ll);
+
+/**
+ * This function creates a list from a string (with separated contents if several)
+ * @param text single string or CSV text fields
+ * @return newly allocated linked list
+ * @note separator is ',' (according to rfc4180, ';' is not valid)
+ **/
+OC_EXPORT OCStringLL* OCCreateOCStringLL(const char* text);
+
+/**
+ * This function creates a string from a list (with separated contents if several)
+ * @param ll Pointer to list
+ * @return newly allocated string
+ * @note separator is ',' (according to rfc4180)
+ **/
+OC_EXPORT char* OCCreateString(const OCStringLL* ll);
#ifdef __cplusplus
}
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags);
+OC_EXPORT OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags);
/**
* This function Initializes the OC Stack. Must be called prior to starting the stack.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode);
+OC_EXPORT OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode);
#ifdef RA_ADAPTER
/**
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCStop();
+OC_EXPORT OCStackResult OCStop();
/**
* This function starts receiving the multicast traffic. This can be only called
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCProcess();
+OC_EXPORT OCStackResult OCProcess();
/**
* This function discovers or Perform requests on a specified resource
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCDoResource(OCDoHandle *handle,
- OCMethod method,
- const char *requestUri,
- const OCDevAddr *destination,
- OCPayload* payload,
- OCConnectivityType connectivityType,
- OCQualityOfService qos,
- OCCallbackData *cbData,
- OCHeaderOption *options,
- uint8_t numOptions);
+OC_EXPORT OCStackResult OCDoResource(OCDoHandle *handle,
+ OCMethod method,
+ const char *requestUri,
+ const OCDevAddr *destination,
+ OCPayload* payload,
+ OCConnectivityType connectivityType,
+ OCQualityOfService qos,
+ OCCallbackData *cbData,
+ OCHeaderOption *options,
+ uint8_t numOptions);
/**
* This function cancels a request associated with a specific @ref OCDoResource invocation.
*
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
- uint8_t numOptions);
+OC_EXPORT OCStackResult OCCancel(OCDoHandle handle,
+ OCQualityOfService qos,
+ OCHeaderOption * options,
+ uint8_t numOptions);
/**
* Register Persistent storage callback.
* OC_STACK_OK No errors; Success.
* OC_STACK_INVALID_PARAM Invalid parameter.
*/
-OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler);
+OC_EXPORT OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler);
#ifdef WITH_PRESENCE
/**
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCStartPresence(const uint32_t ttl);
+OC_EXPORT OCStackResult OCStartPresence(const uint32_t ttl);
/**
* When operating in OCServer or OCClientServer mode, this API will stop sending
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCStopPresence();
+OC_EXPORT OCStackResult OCStopPresence();
#endif
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler, void* callbackParameter);
+OC_EXPORT OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler, void* callbackParameter);
/**
* This function sets device information.
*
- * @param deviceInfo Structure passed by the server application containing the device information.
+ * Upon call to OCInit, the default Device Type (i.e. "rt") has already been set to the default
+ * Device Type "oic.wk.d". You do not have to specify "oic.wk.d" in the OCDeviceInfo.types linked
+ * list. The default Device Type is mandatory and always specified by this Device as the first
+ * Device Type.
+ *
+ * @param deviceInfo Structure passed by the server application containing the device
+ * information.
*
* @return
* ::OC_STACK_OK no errors.
* ::OC_STACK_INVALID_PARAM invalid parameter.
* ::OC_STACK_ERROR stack process error.
*/
-OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo);
+OC_EXPORT OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo);
/**
* This function sets platform information.
* ::OC_STACK_INVALID_PARAM invalid parameter.
* ::OC_STACK_ERROR stack process error.
*/
-OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo);
+OC_EXPORT OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo);
/**
* This function creates a resource.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCCreateResource(OCResourceHandle *handle,
- const char *resourceTypeName,
- const char *resourceInterfaceName,
- const char *uri,
- OCEntityHandler entityHandler,
- void* callbackParam,
- uint8_t resourceProperties);
+OC_EXPORT OCStackResult OCCreateResource(OCResourceHandle *handle,
+ const char *resourceTypeName,
+ const char *resourceInterfaceName,
+ const char *uri,
+ OCEntityHandler entityHandler,
+ void* callbackParam,
+ uint8_t resourceProperties);
/**
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
+OC_EXPORT OCStackResult OCBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
/**
* This function removes a resource from a collection resource.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCUnBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
+OC_EXPORT OCStackResult OCUnBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
/**
* This function binds a resource type to a resource.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
- const char *resourceTypeName);
+OC_EXPORT OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
+ const char *resourceTypeName);
/**
* This function binds a resource interface to a resource.
*
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
- const char *resourceInterfaceName);
+OC_EXPORT OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
+ const char *resourceInterfaceName);
/**
* This function binds an entity handler to the resource.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCBindResourceHandler(OCResourceHandle handle, OCEntityHandler entityHandler,
- void *callbackParameter);
+OC_EXPORT OCStackResult OCBindResourceHandler(OCResourceHandle handle,
+ OCEntityHandler entityHandler,
+ void *callbackParameter);
/**
* This function gets the number of resources that have been created in the stack.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCGetNumberOfResources(uint8_t *numResources);
+OC_EXPORT OCStackResult OCGetNumberOfResources(uint8_t *numResources);
/**
* This function gets a resource handle by index.
*
* @return Found resource handle or NULL if not found.
*/
-OCResourceHandle OCGetResourceHandle(uint8_t index);
+OC_EXPORT OCResourceHandle OCGetResourceHandle(uint8_t index);
/**
* This function deletes resource specified by handle. Deletes resource and all
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCDeleteResource(OCResourceHandle handle);
+OC_EXPORT OCStackResult OCDeleteResource(OCResourceHandle handle);
/**
* Get a string representation the server instance ID.
*
* @return A string representation the server instance ID.
*/
-const char* OCGetServerInstanceIDString(void);
+OC_EXPORT const char* OCGetServerInstanceIDString(void);
/**
* This function gets the URI of the resource specified by handle.
*
* @return URI string if resource found or NULL if not found.
*/
-const char *OCGetResourceUri(OCResourceHandle handle);
+OC_EXPORT const char *OCGetResourceUri(OCResourceHandle handle);
/**
* This function gets the properties of the resource specified by handle.
* @note that after a resource is created, the OC_ACTIVE property is set for the resource by the
* stack.
*/
-OCResourceProperty OCGetResourceProperties(OCResourceHandle handle);
+OC_EXPORT OCResourceProperty OCGetResourceProperties(OCResourceHandle handle);
/**
* This function gets the number of resource types of the resource.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle, uint8_t *numResourceTypes);
+OC_EXPORT OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle, uint8_t *numResourceTypes);
/**
* This function gets name of resource type of the resource.
*
* @return Resource type name if resource found or NULL if resource not found.
*/
-const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index);
+OC_EXPORT const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index);
/**
* This function gets the number of resource interfaces of the resource.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
+OC_EXPORT OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
uint8_t *numResourceInterfaces);
/**
*
* @return Resource interface name if resource found or NULL if resource not found.
*/
-const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index);
+OC_EXPORT const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index);
/**
* This function gets methods of resource interface of the resource.
*
* @return Allowed methods if resource found or NULL if resource not found.
*/
-uint8_t OCGetResourceInterfaceAllowedMethods(OCResourceHandle handle, uint8_t index);
+OC_EXPORT uint8_t OCGetResourceInterfaceAllowedMethods(OCResourceHandle handle, uint8_t index);
/**
* This function gets resource handle from the collection resource by index.
*
* @return Handle to contained resource if resource found or NULL if resource not found.
*/
-OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
+OC_EXPORT OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
uint8_t index);
/**
*
* @return Entity handler if resource found or NULL resource not found.
*/
-OCEntityHandler OCGetResourceHandler(OCResourceHandle handle);
+OC_EXPORT OCEntityHandler OCGetResourceHandler(OCResourceHandle handle);
/**
* This function notify all registered observers that the resource representation has
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos);
+OC_EXPORT OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos);
/**
* Notify specific observers with updated value of representation.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult
+OC_EXPORT OCStackResult
OCNotifyListOfObservers (OCResourceHandle handle,
OCObservationId *obsIdList,
uint8_t numberOfIds,
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCDoResponse(OCEntityHandlerResponse *response);
+OC_EXPORT OCStackResult OCDoResponse(OCEntityHandlerResponse *response);
//#ifdef DIRECT_PAIRING
/**
* client before returning the list of devices.
* @return OCDirectPairingDev_t pointer in case of success and NULL otherwise.
*/
-const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime);
+OC_EXPORT const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime);
/**
* The function is responsible for return of paired device list via direct-pairing. It will list
*
* @return OCDirectPairingDev_t pointer in case of success and NULL otherwise.
*/
-const OCDPDev_t* OCGetDirectPairedDevices();
+OC_EXPORT const OCDPDev_t* OCGetDirectPairedDevices();
/**
* The function is responsible for establishment of direct-pairing. It will proceed mode negotiation
* @param[in] resultCallback Callback fucntion to event status of process.
* @return OTM_SUCCESS in case of success and other value otherwise.
*/
-OCStackResult OCDoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
+OC_EXPORT OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
OCDirectPairingCB resultCallback);
//#endif // DIRECT_PAIRING
#ifdef RA_ADAPTER
#define MAX_ADDR_STR_SIZE (256)
#else
-/** Max Address could be "coap+tcp://[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx]:xxxxx" */
-#define MAX_ADDR_STR_SIZE (59)
+/** Max Address could be
+ * "coap+tcp://[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:yyy.yyy.yyy.yyy]:xxxxx"
+ * +1 for null terminator.
+ */
+#define MAX_ADDR_STR_SIZE (65)
#endif
/** Length of MAC address */
/** 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.*/
char addr[MAX_ADDR_STR_SIZE];
/** usually zero for default interface.*/
- uint32_t interface;
+ uint32_t ifindex;
#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
char routeData[MAX_ADDR_STR_SIZE]; //destination GatewayID:ClientId
#endif
* 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.
{
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;
/**
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
char *uri;
/** Resource Type */
- char *type;
+ OCStringLL *type;
/** Interface */
- OCStringLL *interface;
+ OCStringLL *iface;
/** This structure holds the old /oic/res response. */
OCResourcePayload *resources;
char *sid;
char* deviceName;
char* specVersion;
- char* dataModelVersion;
+ OCStringLL *dataModelVersions;
OCStringLL *interfaces;
OCStringLL *types;
} OCDevicePayload;
OCPayload base;
char* uri;
OCPlatformInfo info;
- char* rt;
+ OCStringLL* rt;
OCStringLL* interfaces;
} OCPlatformPayload;
/** 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;
/**
* 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
#ifdef TB_LOG
#define OIC_LOG_PAYLOAD(level, payload) OCPayloadLog((level),(payload))
#define UUID_SIZE (16)
-const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
-OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
+OC_EXPORT const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
+OC_EXPORT OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
-static inline void OCPayloadLogRep(LogLevel level, OCRepPayload* payload)
+INLINE_API void OCPayloadLogRep(LogLevel level, OCRepPayload* payload)
{
OIC_LOG(level, (PL_TAG), "Payload Type: Representation");
OCRepPayload* rep = payload;
}
-static inline void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* payload)
+INLINE_API void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* payload)
{
OIC_LOG(level, PL_TAG, "Payload Type: Discovery");
int i = 1;
}
if (payload->type)
{
- OIC_LOG_V(level, PL_TAG, "\tResource Type: %s", payload->type);
+ for (OCStringLL *strll = payload->type; strll; strll = strll->next)
+ {
+ OIC_LOG_V(level, PL_TAG, "\tResource Type: %s", strll->value);
+ }
}
OIC_LOG(level, PL_TAG, "\tInterface:");
- for (OCStringLL *itf = payload->interface; itf; itf = itf->next)
+ for (OCStringLL *itf = payload->iface; itf; itf = itf->next)
{
OIC_LOG_V(level, PL_TAG, "\t\t%s", itf->value);
}
}
}
-static inline void OCPayloadLogDevice(LogLevel level, OCDevicePayload* payload)
+INLINE_API void OCPayloadLogDevice(LogLevel level, OCDevicePayload* payload)
{
OIC_LOG(level, PL_TAG, "Payload Type: Device");
OIC_LOG_V(level, PL_TAG, "\tSID:%s", payload->sid);
OIC_LOG_V(level, PL_TAG, "\tDevice Name:%s", payload->deviceName);
- OIC_LOG_V(level, PL_TAG, "\tSpec Version%s", payload->specVersion);
- OIC_LOG_V(level, PL_TAG, "\tData Model Version:%s", payload->dataModelVersion);
+ OIC_LOG_V(level, PL_TAG, "\tSpec Version:%s", payload->specVersion);
+ if (payload->dataModelVersions)
+ {
+ OIC_LOG(level, PL_TAG, "\tData Model Version:");
+ for (OCStringLL *strll = payload->dataModelVersions; strll; strll = strll->next)
+ {
+ OIC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
+ }
+ }
if (payload->types)
{
OIC_LOG(level, PL_TAG, "\tResource Type:");
}
}
-static inline void OCPayloadLogPlatform(LogLevel level, OCPlatformPayload* payload)
+INLINE_API void OCPayloadLogPlatform(LogLevel level, OCPlatformPayload* payload)
{
OIC_LOG(level, PL_TAG, "Payload Type: Platform");
OIC_LOG_V(level, PL_TAG, "\tURI:%s", payload->uri);
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)
{
}
}
-static inline void OCPayloadLogPresence(LogLevel level, OCPresencePayload* payload)
+INLINE_API void OCPayloadLogPresence(LogLevel level, OCPresencePayload* payload)
{
OIC_LOG(level, PL_TAG, "Payload Type: Presence");
OIC_LOG_V(level, PL_TAG, "\tSequence Number:%u", payload->sequenceNumber);
OIC_LOG_V(level, PL_TAG, "\tResource Type:%s", payload->resourceType);
}
-static inline void OCPayloadLogSecurity(LogLevel level, OCSecurityPayload* payload)
+INLINE_API void OCPayloadLogSecurity(LogLevel level, OCSecurityPayload* payload)
{
OIC_LOG(level, PL_TAG, "Payload Type: Security");
OIC_LOG_V(level, PL_TAG, "\tSecurity Data: %s", payload->securityData);
}
-static inline void OCRDPayloadLog(const LogLevel level, const OCRDPayload *payload)
+INLINE_API void OCRDPayloadLog(const LogLevel level, const OCRDPayload *payload)
{
if (!payload)
{
}
}
-static inline void OCPayloadLog(LogLevel level, OCPayload* payload)
+INLINE_API void OCPayloadLog(LogLevel level, OCPayload* payload)
{
if(!payload)
{
* @param level LogLevel for the print.
* @param tags Structure of the tags payload.
*/
-void OCTagsLog(const LogLevel level, const OCTagsPayload *tags);
+OC_EXPORT void OCTagsLog(const LogLevel level, const OCTagsPayload *tags);
/**
* Prints links payload.
* @param level LogLevel for the print.
* @param tags Structure of the links payload.
*/
-void OCLinksLog(const LogLevel level, const OCLinksPayload *links);
+OC_EXPORT void OCLinksLog(const LogLevel level, const OCLinksPayload *links);
#ifdef __cplusplus
}
'../../../../logger/include',
'../../../../stack/include',
'../../../../../../extlibs/cjson',
+ '../../../../../../extlibs/boost/boost',
'../../../../../oc_logger/include',
'../../../../../connectivity/lib/libcoap-4.1.1'
])
-samples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+cc = env.get('CC')
+if cc in ['gcc']:
+ samples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+ samples_env.AppendUnique(LIBS=['-lpthread'])
samples_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
-samples_env.AppendUnique(LIBS = ['-lpthread' ])
samples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-if target_os in ['darwin', 'ios']:
- samples_env.PrependUnique(LIBS = ['m','octbstack', 'ocsrm', 'connectivity_abstraction','coap' ])
-elif target_os not in ['arduino']:
- samples_env.PrependUnique(LIBS = ['m', 'octbstack', 'ocsrm', 'connectivity_abstraction', 'coap'])
+samples_env.PrependUnique(LIBS = ['octbstack', 'ocsrm', 'connectivity_abstraction', 'coap'])
+
+if target_os not in ['arduino', 'windows', 'darwin', 'ios', 'msys_nt']:
samples_env.AppendUnique(LIBS = ['rt'])
+if target_os not in ['windows']:
+ samples_env.PrependUnique(LIBS = ['m'])
+
if env.get('SECURED') == '1':
samples_env.AppendUnique(LIBS = ['tinydtls'])
#include <stdio.h>
#include <stdlib.h>
#include <ocstack.h>
+#include <getopt.h>
const char *getResult(OCStackResult result)
{
--- /dev/null
+#ifndef COMMON_H_
+#define COMMON_H_
+
+const char *getResult(OCStackResult result);
+void StripNewLineChar(char* str);
+
+#endif
#include <stdlib.h>
#include <string.h>
#include <signal.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <iostream>
#include <sstream>
+#include <getopt.h>
#include "ocstack.h"
#include "logger.h"
#include "occlient.h"
#include "ocpayload.h"
#include "payload_logging.h"
+#include "common.h"
+#include "platform_features.h"
#ifdef ROUTING_GATEWAY
/**
static char discoveryAddr[100];
static std::string coapServerResource = "/a/light";
-void StripNewLineChar(char* str);
-
#ifdef WITH_PRESENCE
// The handle for observe registration
OCDoHandle gPresenceHandle;
#include <stdlib.h>
#include <string.h>
#include <signal.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <stdint.h>
#include <sstream>
#include <iostream>
+#include <getopt.h>
#include "ocstack.h"
#include "logger.h"
#include "payload_logging.h"
#include "oic_malloc.h"
#include "oic_string.h"
+#include "common.h"
#define MAX_IP_ADDR_ST_SZ 16 //string size of "155.255.255.255" (15 + 1)
#define MAX_PORT_ST_SZ 6 //string size of "65535" (5 + 1)
#include <stdlib.h>
#include <string.h>
#include <signal.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <ocstack.h>
#include <iostream>
#include <sstream>
+#include <getopt.h>
#include "ocpayload.h"
#include "payload_logging.h"
#include "logger.h"
-const char *getResult(OCStackResult result);
+#include "common.h"
std::string getQueryStrForGetPut();
#define TAG ("occlient")
#include <stdlib.h>
#include <string.h>
#include <signal.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <iostream>
#include <sstream>
+#include <getopt.h>
#include "ocstack.h"
#include "logger.h"
#include "occlientslow.h"
#include "oic_string.h"
#include "ocpayload.h"
#include "payload_logging.h"
+#include "common.h"
// Tracking user input
static int UnicastDiscovery = 0;
//The following variable determines the interface protocol (IP, etc)
//to be used for sending unicast messages. Default set to IP.
-static OCConnectivityType AdapterType = CT_ADAPTER_IP;
+static OCConnectivityType adapterType = CT_ADAPTER_IP;
static OCDevAddr endpoint;
static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res";
-void StripNewLineChar(char* str);
int gQuitFlag = 0;
ret = OCDoResource(NULL, method, query.str().c_str(), dest,
(method == OC_REST_PUT) ? putPayload() : NULL,
- AdapterType, qos, &cbData, options, numOptions);
+ adapterType, qos, &cbData, options, numOptions);
if (ret != OC_STACK_OK)
{
if(ConnectivityType == CT_ADAPTER_DEFAULT || ConnectivityType == CT_IP)
{
- AdapterType = CT_ADAPTER_IP;
+ adapterType = CT_ADAPTER_IP;
}
else
{
OIC_LOG(INFO, TAG, "Default Connectivity type selected...");
- AdapterType = CT_ADAPTER_IP;
+ adapterType = CT_ADAPTER_IP;
}
InitDiscovery();
#include "ocpayload.h"
#include "payload_logging.h"
#include "ocremoteaccessclient.h"
+#include "common.h"
#define SET_BUT_NOT_USED(x) (void) x
// Tracking user input
static OCDevAddr responseAddr;
//Use ipv4addr for both InitDiscovery and InitPlatformOrDeviceDiscovery
char remoteServerJabberID[MAX_ADDR_STR_SIZE];
-void StripNewLineChar(char* str);
static uint16_t maxNotification = 15;
// The handle for the observe registration
#include <string.h>
#include <string>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <signal.h>
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
#include <array>
+#include "oic_malloc.h"
+#include <getopt.h>
#include "ocstack.h"
#include "logger.h"
#include "ocpayload.h"
#include "ocserver.h"
+#include "common.h"
+#include "platform_features.h"
//string length of "/a/light/" + std::numeric_limits<int>::digits10 + '\0'"
// 9 + 9 + 1 = 19
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
OCStackResult result = OC_STACK_ERROR;
uint8_t j = 0;
- uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2;
- OCObservationId obsNotify[numNotifies];
+ OCObservationId obsNotify[(SAMPLE_MAX_NUM_OBSERVATIONS)/2];
while (!gQuitFlag)
{
void DeleteDeviceInfo()
{
free (deviceInfo.deviceName);
+ free (deviceInfo.specVersion);
+ OCFreeOCStringLL (deviceInfo.dataModelVersions);
}
bool DuplicateString(char** targetString, const char* sourceString)
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;
}
exit (EXIT_FAILURE);
}
- registrationResult = SetDeviceInfo(deviceName);
+ registrationResult = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
if (registrationResult != OC_STACK_OK)
{
if (observeThreadStarted)
{
+#ifdef HAVE_PTHREAD_H
pthread_cancel(threadId_observe);
pthread_join(threadId_observe, NULL);
+#endif
}
+#ifdef HAVE_PTHREAD_H
pthread_cancel(threadId_presence);
pthread_join(threadId_presence, NULL);
+#endif
OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <signal.h>
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
#include "ocstack.h"
#include "logger.h"
#include "ocserverbasicops.h"
#include <string.h>
#include <string>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <signal.h>
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
#include <ocstack.h>
#include <logger.h>
+#include <getopt.h>
#include "ocpayload.h"
-
-const char *getResult(OCStackResult result);
+#include "common.h"
+#include "platform_features.h"
#define TAG PCF("ocservercontainer")
/*
* Cancel the light thread and wait for it to terminate
*/
+#ifdef HAVE_PTHREAD_H
pthread_cancel(threadId);
pthread_join(threadId, NULL);
+#endif
OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <signal.h>
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
+#include <boost/config.hpp>
#include <list>
#include "ocstack.h"
#include "oic_malloc.h"
volatile sig_atomic_t gQuitFlag = 0;
static std::list<OCEntityHandlerRequest *> gRequestList;
-static constexpr unsigned int SLOW_RESPONSE_DELAY_SEC = 5;
+BOOST_STATIC_CONSTEXPR unsigned int SLOW_RESPONSE_DELAY_SEC = 5;
static LEDResource LED;
-static constexpr unsigned int SAMPLE_MAX_NUM_POST_INSTANCE = 2;
+BOOST_STATIC_CONSTEXPR unsigned int SAMPLE_MAX_NUM_POST_INSTANCE = 2;
static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
//char *gResourceUri= const_cast<char *>("/a/led");
return copyOfRequest;
}
+#if !defined(SIGALRM)
+void AlarmHandler(int sig);
+int WINAPI AlarmThread(void *seconds)
+{
+ sleep((unsigned int)seconds);
+ AlarmHandler(0);
+ return 0;
+}
+
+void alarm(unsigned int seconds)
+{
+ CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)AlarmThread, (void*)seconds, 0, NULL);
+}
+#endif
+
OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
OCEntityHandlerRequest *entityHandlerRequest, void* /*callbackParam*/)
{
// slow response when fired
void AlarmHandler(int sig)
{
+#ifdef SIGALRM
if (sig == SIGALRM)
+#endif
{
OIC_LOG (INFO, TAG, "Server starting slow response");
if (gRequestList.empty())
// Declare and create the example resource: LED
createLEDResource(gResourceUri, &LED, false, 42);
+#ifdef SIGALRM
// Initialize slow response alarm
signal(SIGALRM, AlarmHandler);
+#endif
// Break from loop with Ctrl-C
OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
])
target_os = env.get('TARGET_OS')
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
samples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
# Note: 'pthread' is in libc for android.
if target_os != 'android':
samples_env.AppendUnique(LIBS = ['-lpthread'])
+ samples_env.Append(LINKFLAGS = ['-Wl,--no-as-needed'])
samples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-samples_env.PrependUnique(LIBS = ['octbstack', 'm', 'connectivity_abstraction', 'coap'])
+if target_os in ['windows', 'msys_nt']:
+ samples_env.PrependUnique(LIBS = ['ocsrm', 'ws2_32', 'iphlpapi'])
+else:
+ samples_env.PrependUnique(LIBS = ['m'])
+samples_env.PrependUnique(LIBS = ['octbstack', 'connectivity_abstraction', 'coap'])
if env.get('SECURED') == '1':
samples_env.AppendUnique(LIBS = ['tinydtls'])
-samples_env.Append(LINKFLAGS = ['-Wl,--no-as-needed'])
-
if target_os == 'android':
samples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
samples_env.AppendUnique(LIBS = ['gnustl_shared'])
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
#include <signal.h>
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#include "platform_features.h"
#include "ocstack.h"
#include "logger.h"
#include "common.h"
#include <stdlib.h>
#include <string.h>
#include <signal.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+/** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
+#ifdef ERROR
+#undef ERROR
+#endif
+#endif
#include <iostream>
#include <sstream>
+#include <getopt.h>
+#include "platform_features.h"
#include "ocstack.h"
#include "logger.h"
#include "occlientbasicops.h"
//of other devices which the client trusts
static char CRED_FILE_DEVOWNER[] = "oic_svr_db_client_devowner.dat";
static char CRED_FILE_NONDEVOWNER[] = "oic_svr_db_client_nondevowner.dat";
-
+const char * OIC_RSRC_DOXM_URI = "/oic/sec/doxm";
+const char * OIC_RSRC_PSTAT_URI = "/oic/sec/pstat";
int gQuitFlag = 0;
OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
- OIC_LOG(INFO, TAG, "-d 0 : Client as Device Owner");
- OIC_LOG(INFO, TAG, "-d 1 : Client as Non Device Owner");
+ OIC_LOG(INFO, TAG, "-d 0 : Client as Non Device Owner");
+ OIC_LOG(INFO, TAG, "-d 1 : Client as Device Owner");
}
OCStackResult InvokeOCDoResource(std::ostringstream &query,
{
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;
}
#include <stdlib.h>\r
#include <string.h>\r
#include <signal.h>\r
+#ifdef HAVE_UNISTD_H\r
#include <unistd.h>\r
+#endif\r
+#ifdef HAVE_PTHREAD_H\r
#include <pthread.h>\r
+#endif\r
#include <iostream>\r
#include <sstream>\r
+#if defined(HAVE_WINDOWS_H)\r
+#include <windows.h>\r
+/** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */\r
+#ifdef ERROR\r
+#undef ERROR\r
+#endif\r
+#endif // defined(HAVE_WINDOWS_H)\r
+#include "platform_features.h"\r
#include "ocstack.h"\r
#include "logger.h"\r
#include "ocpayload.h"\r
}\r
\r
// This is a function called back when direct-pairing status is changed\r
-void pairingReqCB(OCDPDev_t* peer, OCStackResult result)\r
+void pairingReqCB(void *ctx, OCDPDev_t* peer, OCStackResult result)\r
{\r
OIC_LOG(INFO, TAG, "Callback Context for Direct-Pairing establishment\n");\r
\r
+ (void) ctx;\r
if (OC_STACK_OK == result)\r
{\r
OIC_LOG_V(INFO, TAG,\r
\r
// start direct pairing\r
OIC_LOG(INFO, TAG, " Start Direct Pairing..");\r
- if(OC_STACK_OK != OCDoDirectPairing(peer, pmSel, pinNumber, pairingReqCB))\r
+ if(OC_STACK_OK != OCDoDirectPairing(NULL, peer, pmSel, pinNumber, pairingReqCB))\r
{\r
OIC_LOG(ERROR, TAG, "OCDoDirectPairing API error");\r
return OC_STACK_ERROR;\r
\r
void *CLInterface(void *data)\r
{\r
- printf(RED_BEGIN"#Ready to operation ('h' for help)#\n"COLOR_END);\r
+ printf(RED_BEGIN "#Ready to operation ('h' for help)#\n" COLOR_END);\r
\r
(void)data;\r
OCStackResult ret;\r
- char query[MAX_LINE] = {0,};\r
- const char prompt[] = BOLD_BEGIN"IoTivity-DP#"COLOR_END" ";\r
+ char query[MAX_LINE] = {0};\r
+ const char prompt[] = BOLD_BEGIN "IoTivity-DP#" COLOR_END" ";\r
const char* helpmsg[6] = {\r
- GREEN_BEGIN"# h (or help) : show help message"COLOR_END,\r
- GREEN_BEGIN"# dd (DP device discovery) : discover Direct-Pairing devices"COLOR_END,\r
- GREEN_BEGIN"# dp (start Direct-Pairing) : negotiate DP method & start Direct-Pairing"COLOR_END,\r
- GREEN_BEGIN"# sd (send data) : send data to device"COLOR_END,\r
- GREEN_BEGIN"# ll (list all device) : list all discovered/paired devices"COLOR_END,\r
- GREEN_BEGIN"# q (quit) : quit test"COLOR_END,\r
+ GREEN_BEGIN "# h (or help) : show help message" COLOR_END,\r
+ GREEN_BEGIN "# dd (DP device discovery) : discover Direct-Pairing devices" COLOR_END,\r
+ GREEN_BEGIN "# dp (start Direct-Pairing) : negotiate DP method & start Direct-Pairing" COLOR_END,\r
+ GREEN_BEGIN "# sd (send data) : send data to device" COLOR_END,\r
+ GREEN_BEGIN "# ll (list all device) : list all discovered/paired devices" COLOR_END,\r
+ GREEN_BEGIN "# q (quit) : quit test" COLOR_END,\r
};\r
\r
for (size_t i=0; i<(sizeof(helpmsg)/sizeof(char*)); i++)\r
return 0;\r
}\r
\r
+#if defined(_WIN32)\r
+ Sleep(100);\r
+#else\r
nanosleep(&timeout, NULL);\r
+#endif // defined(_WIN32)\r
+\r
}\r
OIC_LOG(INFO, TAG, "Exiting occlient main loop...");\r
\r
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <signal.h>
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#include "platform_features.h"
#include "ocstack.h"
#include "logger.h"
#include "ocpayload.h"
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
},\r
{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/ad",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.ad"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/amacl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.amacl"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } ,\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
"deviceuuid": "31393139-3139-3139-3139-313931393139",\r
"devowneruuid": "61646D69-6E44-6576-6963-655555494430",\r
"rowneruuid": "31393139-3139-3139-3139-313931393139",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
},\r
"cred": {\r
"creds": [\r
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
},\r
{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/ad",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.ad"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/amacl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.amacl"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } ,\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
"deviceuuid": "32323232-3232-3232-3232-323232323232",\r
"devowneruuid": "32323232-3232-3232-3232-323232323232",\r
"rowneruuid": "32323232-3232-3232-3232-323232323232",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
},\r
"cred": {\r
"creds": [\r
{
- "acl": {\r
- "aclist": {\r
- "aces": [\r
- {\r
- "subjectuuid": "*",\r
- "resources": [\r
- {\r
- "href": "/oic/res",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/p",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/presence",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- }\r
- ],\r
- "permission": 2\r
- },\r
- {\r
- "subjectuuid": "*",\r
- "resources": [\r
- {\r
- "href": "/oic/sec/doxm",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/sec/pstat",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/sec/acl",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/sec/cred",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- }\r
- ],\r
- "permission": 6\r
- }\r
- ]\r
- },\r
- "rowneruuid" : "64697265-6374-7061-6972-696e67446576"\r
- },\r
- "pstat": {\r
- "isop": false,\r
- "deviceuuid": "64697265-6374-7061-6972-696e67446576",\r
- "rowneruuid": "64697265-6374-7061-6972-696e67446576",\r
- "cm": 2,\r
- "tm": 0,\r
- "om": 3,\r
- "sm": 3\r
- },\r
- "doxm": {\r
- "oxms": [0],\r
- "oxmsel": 0,\r
- "sct": 1,\r
- "owned": false,\r
- "deviceuuid": "64697265-6374-7061-6972-696e67446576",\r
- "devowneruuid": "",\r
- "rowneruuid": "64697265-6374-7061-6972-696e67446576",\r
- "dpc": false\r
+ "acl": {
+ "aclist": {
+ "aces": [
+ {
+ "subjectuuid": "*",
+ "resources": [
+ {
+ "href": "/oic/res",
+ "rel": "",
+ "rt": ["oic.wk.res"],
+ "if": ["oic.if.ll"]
+ },
+ {
+ "href": "/oic/d",
+ "rel": "",
+ "rt": ["oic.wk.d"],
+ "if": ["oic.if.baseline", "oic.if.r"]
+ },
+ {
+ "href": "/oic/p",
+ "rel": "",
+ "rt": ["oic.wk.p"],
+ "if": ["oic.if.baseline", "oic.if.r"]
+ }
+ ],
+ "permission": 2
+ },
+ {
+ "subjectuuid": "*",
+ "resources": [
+ {
+ "href": "/oic/sec/doxm",
+ "rel": "",
+ "rt": ["oic.r.doxm"],
+ "if": ["oic.if.baseline"]
+ },
+ {
+ "href": "/oic/sec/pstat",
+ "rel": "",
+ "rt": ["oic.r.pstat"],
+ "if": ["oic.if.baseline"]
+ },
+ {
+ "href": "/oic/sec/acl",
+ "rel": "",
+ "rt": ["oic.r.acl"],
+ "if": ["oic.if.baseline"]
+ },
+ {
+ "href": "/oic/sec/cred",
+ "rel": "",
+ "rt": ["oic.r.cred"],
+ "if": ["oic.if.baseline"]
+ }
+ ],
+ "permission": 6
+ }
+ ]
+ },
+ "rowneruuid" : "64697265-6374-7061-6972-696e67446576"
+ },
+ "pstat": {
+ "isop": false,
+ "deviceuuid": "64697265-6374-7061-6972-696e67446576",
+ "rowneruuid": "64697265-6374-7061-6972-696e67446576",
+ "cm": 2,
+ "tm": 0,
+ "om": 3,
+ "sm": 3
+ },
+ "doxm": {
+ "oxms": [0],
+ "oxmsel": 0,
+ "sct": 1,
+ "owned": false,
+ "deviceuuid": "64697265-6374-7061-6972-696e67446576",
+ "devowneruuid": "",
+ "rowneruuid": "64697265-6374-7061-6972-696e67446576",
+ "x.com.samsung.dpc": false\r
}\r
}\r
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
},\r
{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/ad",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.ad"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/amacl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.amacl"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } ,\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
"deviceuuid": "31393139-3139-3139-3139-313931393139",\r
"devowneruuid": "31393139-3139-3139-3139-313931393139",\r
"rowneruuid": "31393139-3139-3139-3139-313931393139",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
},\r
"cred": {\r
"creds": [\r
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
},\r
{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/ad",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.ad"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/amacl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.amacl"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } ,\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } ,\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
{\r
"href": "/oic/sec/cred",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.cred"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 8\r
{\r
"href": "/a/led",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.core"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
- "permission": 6,\r
- "period" : ["20150630T060000/20150630T220000", "20150630T060000/20150630T200000"],\r
- "recurrence" : ["FREQ=DAILY; BYDAY=MO, WE, FR", "FREQ=DAILY; BYDAY=TU, TH; UNTIL=20160630"]\r
+ "permission": 6\r
},\r
{\r
"subjectuuid": "37373737-3737-3737-3737-373737373737",\r
{\r
"href": "/a/led",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.core"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
- "permission": 6,\r
- "period" : ["20150630T060000/20150630T220000"],\r
- "recurrence" : ["FREQ=DAILY; UNTIL=20150630"]\r
+ "permission": 6\r
}\r
]\r
},\r
"deviceuuid": "31313131-3131-3131-3131-313131313131",\r
"devowneruuid": "32323232-3232-3232-3232-323232323232",\r
"rowneruuid": "31313131-3131-3131-3131-313131313131",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
},\r
"cred": {\r
"creds": [\r
# Map of host os and allowed target os (host: allowed target os)
host_target_map = {
'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
- 'windows': ['windows', 'winrt', 'android', 'arduino', 'tizen'],
+ 'windows': ['windows', 'android', 'arduino', 'tizen'],
'darwin': ['darwin', 'ios', 'android', 'arduino'],
}
'linux': ['x86', 'x86_64', 'arm', 'arm64'],
'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
'windows': ['x86', 'amd64', 'arm'],
- 'winrt': ['arm'],
'darwin': ['i386', 'x86_64'],
'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
'arduino': ['avr', 'arm'],
#include <signal.h>
#include <pthread.h>
#include <array>
+#include "oic_malloc.h"
#include "ocstack.h"
#include "logger.h"
#include "ocpayload.h"
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
void DeleteDeviceInfo()
{
free (deviceInfo.deviceName);
+ free (deviceInfo.specVersion);
+ OCFreeOCStringLL (deviceInfo.dataModelVersions);
}
bool DuplicateString(char** targetString, const char* sourceString)
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;
}
exit (EXIT_FAILURE);
}
- registrationResult = SetDeviceInfo(deviceName);
+ registrationResult = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
if (registrationResult != OC_STACK_OK)
{
%define ROOTDIR %{_builddir}/%{name}-%{version}
Name: com-oic-ri-sample
-Version: 0.1
-Release: 1
+Version: 1.1.1
+Release: 0
Summary: Tizen adapter interfacesample application
URL: http://slp-source.sec.samsung.net
Source: %{name}-%{version}.tar.gz
%define DEST_LIB_DIR %{buildroot}/%{_libdir}
Name: com-oic-ri
-Version: 0.1
-Release: 1
+Version: 1.1.1
+Release: 0
Summary: Tizen oicri application
URL: http://slp-source.sec.samsung.net
Source: %{name}-%{version}.tar.gz
cp -f %{ROOTDIR}/resource/csdk/connectivity/lib/libcoap-4.1.1/libcoap.a %{buildroot}/%{_libdir}
cp /usr/lib/libuuid.so.1 %{buildroot}%{_libdir}
if echo %{SECURED}|grep -qi '1'; then
- cp -f %{ROOTDIR}/extlibs/tinydtls/libtinydtls.a %{buildroot}/%{_libdir}
+ cp -f %{ROOTDIR}/out/tizen/*/*/extlibs/tinydtls/libtinydtls.a %{buildroot}/%{_libdir}
fi
cp -rf %{ROOTDIR}/resource/csdk/stack/include/ocstack.h* %{DEST_INC_DIR}/
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}
#include "oic_malloc.h"
#include <string.h>
-#ifdef WITH_ARDUINO
-#include "Time.h"
-#else
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
+#ifdef HAVE_ARDUINO_TIME_H
+#include "Time.h"
+#endif
#include "coap_time.h"
#include "cacommon.h"
#define NUM_PARAM_IN_QUERY 2 // The expected number of parameters in a query
#define NUM_FIELDS_IN_QUERY 2 // The expected number of fields in a query
+#include "platform_features.h"
+
static OCStackResult CheckRTParamSupport(const OCResource* resource, const char* rtPtr)
{
if (!resource || !rtPtr)
request->numRcvdVendorSpecificHeaderOptions,
request->rcvdVendorSpecificHeaderOptions,
OC_OBSERVE_NO_OPTION,
- 0);
+ 0,
+ request->coapID);
if (result == OC_STACK_OK)
{
ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest,
return OC_STACK_RESOURCE_ERROR;
}
- if (!resUri || !token || !*token)
+ if (!resUri || !token)
{
return OC_STACK_INVALID_PARAM;
}
{
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);
OCStackResult DeleteObserverUsingToken (CAToken_t token, uint8_t tokenLength)
{
- if (!token || !*token)
+ if (!token)
{
return OC_STACK_INVALID_PARAM;
}
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+// Required for strok_r
+#define _POSIX_C_SOURCE 200112L
+#include <stdio.h>
#include "ocpayload.h"
#include "octypes.h"
#include <string.h>
#include "rdpayload.h"
#define TAG "OIC_RI_PAYLOAD"
+#define CSV_SEPARATOR ','
static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val);
case OCREP_PROP_STRING:
dest->str = OICStrdup(source->str);
break;
+ case OCREP_PROP_BYTE_STRING:
+ dest->ocByteStr.bytes = (uint8_t*)OICMalloc(source->ocByteStr.len * sizeof(uint8_t));
+ VERIFY_PARAM_NON_NULL(TAG, dest->ocByteStr.bytes, "Failed allocating memory");
+ dest->ocByteStr.len = source->ocByteStr.len;
+ memcpy(dest->ocByteStr.bytes, source->ocByteStr.bytes, dest->ocByteStr.len);
+ break;
case OCREP_PROP_OBJECT:
dest->obj = OCRepPayloadClone(source->obj);
break;
// Nothing to do for the trivially copyable types.
break;
}
+exit:
+ return;
}
static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val)
}
}
-bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* interface)
+bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* iface)
{
- return OCRepPayloadAddInterfaceAsOwner(payload, OICStrdup(interface));
+ return OCRepPayloadAddInterfaceAsOwner(payload, OICStrdup(iface));
}
-bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface)
+bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* iface)
{
- if (!payload || !interface)
+ if (!payload || !iface)
{
return false;
}
{
return false;
}
- cur->next->value = interface;
+ cur->next->value = iface;
return true;
}
else
{
return false;
}
- payload->interfaces->value = interface;
+ payload->interfaces->value = iface;
return true;
}
}
{
if (!array)
{
- return NULL;
+ return false;
}
size_t dimTotal = calcDimTotal(dimensions);
return false;
}
- if (val->arr.type != OCREP_PROP_DOUBLE)
+ if (val->arr.type == OCREP_PROP_DOUBLE)
{
memcpy(*array, val->arr.dArray, dimTotal * sizeof(double));
}
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)
return NULL;
}
+#ifndef TCP_ADAPTER
+static OCResourcePayload* OCCopyResource(const OCResource* res, uint16_t securePort)
+#else
static OCResourcePayload* OCCopyResource(const OCResource* res, uint16_t securePort,
uint16_t tcpPort)
+#endif
{
OCResourcePayload* pl = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
if (!pl)
return pl;
}
+#ifndef TCP_ADAPTER
+void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
+ uint16_t securePort)
+{
+ OCDiscoveryPayloadAddNewResource(payload, OCCopyResource(res, securePort));
+}
+#else
void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
uint16_t securePort, uint16_t tcpPort)
{
OCDiscoveryPayloadAddNewResource(payload, OCCopyResource(res, securePort, tcpPort));
}
+#endif
bool OCResourcePayloadAddStringLL(OCStringLL **stringLL, const char *value)
{
OICFree(payload->sid);
OICFree(payload->baseURI);
OICFree(payload->uri);
- OICFree(payload->type);
+ OCFreeOCStringLL(payload->type);
OICFree(payload->name);
- OCFreeOCStringLL(payload->interface);
+ OCFreeOCStringLL(payload->iface);
OCDiscoveryResourceDestroy(payload->resources);
OICFree(payload);
}
goto exit;
}
- payload->dataModelVersion = OICStrdup(dmVer);
- if (dmVer && !payload->dataModelVersion)
+ payload->dataModelVersions = OCCreateOCStringLL(dmVer);
+ if (!payload->dataModelVersions || (dmVer && !payload->dataModelVersions->value))
{
goto exit;
}
OICFree(payload->sid);
OICFree(payload->deviceName);
OICFree(payload->specVersion);
- OICFree(payload->dataModelVersion);
+ OCFreeOCStringLL(payload->dataModelVersions);
OCFreeOCStringLL(payload->types);
OCFreeOCStringLL(payload->interfaces);
OICFree(payload);
return NULL;
}
payload->interfaces->value = OICStrdup(OC_RSRVD_INTERFACE_READ);
- payload->rt = OICStrdup(OC_RSRVD_RESOURCE_TYPE_PLATFORM);
+ payload->rt = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
+ if (!payload->rt)
+ {
+ return NULL;
+ }
+ payload->rt->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_PLATFORM);
payload->info = *platformInfo;
return payload;
}
payload->base.type = PAYLOAD_TYPE_PLATFORM;
- payload->rt = OICStrdup(OC_RSRVD_RESOURCE_TYPE_PLATFORM);
+ OCResourcePayloadAddStringLL(&payload->rt, OC_RSRVD_RESOURCE_TYPE_PLATFORM);
OCResourcePayloadAddStringLL(&payload->interfaces, OC_RSRVD_INTERFACE_DEFAULT);
OCResourcePayloadAddStringLL(&payload->interfaces, OC_RSRVD_INTERFACE_READ);
}
OICFree(payload->uri);
OCPlatformInfoDestroy(&payload->info);
- OICFree(payload->rt);
+ OCFreeOCStringLL(payload->rt);
OCFreeOCStringLL(payload->interfaces);
OICFree(payload);
}
// 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,
// TinyCbor Version 47a78569c0 or better on master is required for the re-allocation
// strategy to work. If you receive the following assertion error, please do a git-pull
// from the extlibs/tinycbor/tinycbor directory
- #define CborNeedsUpdating (CborErrorOutOfMemory < CborErrorDataTooLarge)
+ #define CborNeedsUpdating (((unsigned int)CborErrorOutOfMemory) < ((unsigned int)CborErrorDataTooLarge))
OC_STATIC_ASSERT(!CborNeedsUpdating, "tinycbor needs to be updated to at least 47a78569c0");
#undef CborNeedsUpdating
[ // 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",
sizeof(OC_RSRVD_DEVICE_NAME) - 1, payload->name);
VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting name");
- // Insert URI
- err |= ConditionalAddTextStringToMap(&rootMap, OC_RSRVD_HREF, sizeof(OC_RSRVD_HREF) - 1,
- payload->uri);
- VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting href");
-
// Insert Device ID into the root map
err |= AddTextStringToMap(&rootMap, OC_RSRVD_DEVICE_ID, sizeof(OC_RSRVD_DEVICE_ID) - 1,
payload->sid);
VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting device id");
// Insert Resource Type
- err |= ConditionalAddTextStringToMap(&rootMap, OC_RSRVD_RESOURCE_TYPE,
- sizeof(OC_RSRVD_RESOURCE_TYPE) - 1, payload->type);
+ err |= OCStringLLJoin(&rootMap, OC_RSRVD_RESOURCE_TYPE, payload->type);
VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting RT");
// Insert interfaces
- if (payload->interface)
+ if (payload->iface)
{
- err |= OCStringLLJoin(&rootMap, OC_RSRVD_INTERFACE, payload->interface);
+ err |= OCStringLLJoin(&rootMap, OC_RSRVD_INTERFACE, payload->iface);
VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding interface types tag/value");
}
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);
}
int64_t err = CborNoError;
CborEncoder encoder;
+ char *dataModelVersions = 0;
cbor_encoder_init(&encoder, outPayload, *size, 0);
CborEncoder repMap;
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");
// 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.");
}
#include "ocstackinternal.h"
#include "payload_logging.h"
#include "rdpayload.h"
+#include "platform_features.h"
#define TAG "OIC_RI_PAYLOADPARSE"
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");
}
err = cbor_value_map_find_value(&rootMap, OC_RSRVD_INTERFACE, &curVal);
if (cbor_value_is_valid(&curVal))
{
- err = OCParseStringLL(&rootMap, OC_RSRVD_INTERFACE, &out->interface);
+ err = OCParseStringLL(&rootMap, OC_RSRVD_INTERFACE, &out->iface);
}
- if (!out->interface)
+ if (!out->iface)
{
- if (!OCResourcePayloadAddStringLL(&out->interface, OC_RSRVD_INTERFACE_LL))
+ if (!OCResourcePayloadAddStringLL(&out->iface, OC_RSRVD_INTERFACE_LL))
{
err = CborErrorOutOfMemory;
}
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");
OCStackResult ret = OC_STACK_INVALID_PARAM;
CborError err = CborNoError;
OCPlatformInfo info = {0};
- char* rt = NULL;
+ OCStringLL* rt = NULL;
OCStringLL* interfaces = NULL;
OCPlatformPayload* out = NULL;
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");
}
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
// Refer http://pubs.opengroup.org/onlinepubs/009695399/
#define _POSIX_C_SOURCE 200112L
-#ifdef WITH_ARDUINO
+#ifdef WITH_STRING_H
#include <string.h>
-#else
+#endif
+#ifdef WITH_STRINGS_H
#include <strings.h>
#endif
#define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
TAG, #arg " is NULL"); return (retVal); } }
+#include "platform_features.h"
+
extern OCResource *headResource;
static OCPlatformInfo savedPlatformInfo = {0};
static OCDeviceInfo savedDeviceInfo = {0};
{
tcpPort = 0;
}
+ OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
+#else
+ OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort);
#endif
- OCDiscoveryPayloadAddResource(payload, resourcePtr, securePort, tcpPort);
return OC_STACK_OK;
}
}
OCStackResult discoveryResult = OC_STACK_ERROR;
-
- bool bMulticast = false; // Was the discovery request a multicast request?
OCPayload* payload = NULL;
OIC_LOG(INFO, TAG, "Entering HandleVirtualResource");
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;
}
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);
discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
}
- discPayload->type = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
+ discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
- OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_LL);
- OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_DEFAULT);
- VERIFY_NON_NULL(discPayload->interface, ERROR, OC_STACK_NO_MEMORY);
+ discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
+ VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
+ OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
+ OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
+ VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
}
bool foundResourceAtRD = false;
for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
}
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);
}
}
}
{
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. ");
}
}
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
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)
}
else
{
- result = OC_STACK_OK;
-
// The error in observeResult for the request will be used when responding to this
// request by omitting the observation option/sequence number.
request->observeResult = OC_STACK_ERROR;
OIC_LOG(ERROR, TAG, "Observer Addition failed");
ehFlag = OC_REQUEST_FLAG;
+ FindAndDeleteServerRequest(request);
+ goto exit;
}
}
}
else
{
- result = OC_STACK_OK;
request->observeResult = OC_STACK_ERROR;
OIC_LOG(ERROR, TAG, "Observer Removal failed");
+ FindAndDeleteServerRequest(request);
+ goto exit;
}
}
else
request->numRcvdVendorSpecificHeaderOptions,
request->rcvdVendorSpecificHeaderOptions,
(OCObserveAction)request->observationOption,
- (OCObservationId)0);
+ (OCObservationId)0,
+ request->coapID);
if(result == OC_STACK_OK)
{
result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
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)
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;
}
uint8_t numVendorOptions,
OCHeaderOption * vendorOptions,
OCObserveAction observeAction,
- OCObservationId observeID)
+ OCObservationId observeID,
+ uint16_t messageID)
{
if (entityHandlerRequest)
{
entityHandlerRequest->query = queryBuf;
entityHandlerRequest->obsInfo.action = observeAction;
entityHandlerRequest->obsInfo.obsId = observeID;
+ entityHandlerRequest->messageID = messageID;
if(payload && payloadSize)
{
CAResponseResult_t ConvertEHResultToCAResult (OCEntityHandlerResult result, OCMethod method)
{
- CAResponseResult_t caResult;
+ CAResponseResult_t caResult = CA_BAD_REQ;
switch (result)
{
- case OC_EH_OK:
- switch (method)
- {
- case OC_REST_PUT:
- case OC_REST_POST:
- // This Response Code is like HTTP 204 "No Content" but only used in
- // response to POST and PUT requests.
- caResult = CA_CHANGED;
- break;
- case OC_REST_GET:
- // This Response Code is like HTTP 200 "OK" but only used in response to
- // GET requests.
- caResult = CA_CONTENT;
- break;
- default:
- // This should not happen but,
- // give it a value just in case but output an error
- caResult = CA_CONTENT;
- OIC_LOG_V(ERROR, TAG, "Unexpected OC_EH_OK return code for method [%d].", method);
- }
+ // Successful Client Request
+ case OC_EH_RESOURCE_CREATED: // 2.01
+ if (method == OC_REST_POST || method == OC_REST_PUT)
+ {
+ caResult = CA_CREATED;
+ }
break;
- case OC_EH_ERROR:
- caResult = CA_BAD_REQ;
+ case OC_EH_RESOURCE_DELETED: // 2.02
+ if (method == OC_REST_POST || method == OC_REST_DELETE)
+ {
+ caResult = CA_DELETED;
+ }
break;
- case OC_EH_RESOURCE_CREATED:
- caResult = CA_CREATED;
+ case OC_EH_SLOW: // 2.05
+ caResult = CA_CONTENT;
break;
- case OC_EH_RESOURCE_DELETED:
- caResult = CA_DELETED;
+ case OC_EH_OK: // 2.04/2.05
+ if (method == OC_REST_POST || method == OC_REST_PUT)
+ {
+ caResult = CA_CHANGED;
+ }
+ else if (method == OC_REST_GET)
+ {
+ caResult = CA_CONTENT;
+ }
break;
- case OC_EH_SLOW:
- caResult = CA_CONTENT;
+ case OC_EH_VALID: // 2.03
+ caResult = CA_VALID;
break;
- case OC_EH_FORBIDDEN:
+ case OC_EH_CHANGED: // 2.04
+ caResult = CA_CHANGED;
+ break;
+ // Unsuccessful Client Request
+ case OC_EH_UNAUTHORIZED_REQ: // 4.01
caResult = CA_UNAUTHORIZED_REQ;
break;
- case OC_EH_RESOURCE_NOT_FOUND:
+ case OC_EH_BAD_OPT: // 4.02
+ caResult = CA_BAD_OPT;
+ break;
+ case OC_EH_FORBIDDEN: // 4.03
+ caResult = CA_FORBIDDEN_REQ;
+ break;
+ case OC_EH_RESOURCE_NOT_FOUND: // 4.04
caResult = CA_NOT_FOUND;
break;
+ case OC_EH_METHOD_NOT_ALLOWED: // 4.05
+ caResult = CA_METHOD_NOT_ALLOWED;
+ break;
+ case OC_EH_NOT_ACCEPTABLE: // 4.06
+ caResult = CA_NOT_ACCEPTABLE;
+ break;
+ case OC_EH_INTERNAL_SERVER_ERROR: // 5.00
+ caResult = CA_INTERNAL_SERVER_ERROR;
+ break;
+ case OC_EH_RETRANSMIT_TIMEOUT: // 5.04
+ caResult = CA_RETRANSMIT_TIMEOUT;
+ break;
default:
caResult = CA_BAD_REQ;
break;
CopyDevAddrToEndpoint(&serverRequest->devAddr, &responseEndpoint);
+ responseInfo.info.messageId = serverRequest->coapID;
responseInfo.info.resourceUri = serverRequest->resourceUrl;
responseInfo.result = ConvertEHResultToCAResult(ehResponse->ehResult, serverRequest->method);
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)
responseInfo.info.type = CA_MSG_NONCONFIRM;
}
- char rspToken[CA_MAX_TOKEN_LEN + 1] = {};
+ char rspToken[CA_MAX_TOKEN_LEN + 1] = {0};
responseInfo.info.messageId = serverRequest->coapID;
responseInfo.info.token = (CAToken_t)rspToken;
memcpy(responseInfo.info.token, serverRequest->requestToken, serverRequest->tokenLength);
responseInfo.info.tokenLength = serverRequest->tokenLength;
- if(serverRequest->observeResult == OC_STACK_OK)
+ // De-register observe option should not be included in the response header
+ if((serverRequest->observeResult == OC_STACK_OK) && (serverRequest->observationOption != OC_OBSERVE_DEREGISTER))
{
responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
}
(OCRepPayload*)newPayload);
}
-
(serverRequest->numResponses)--;
if(serverRequest->numResponses == 0)
exit:
return stackRet;
}
-
#include "directpairing.h"
//#endif
-#ifdef WITH_ARDUINO
+#ifdef HAVE_ARDUINO_TIME_H
#include "Time.h"
-#else
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include "coap_time.h"
#include "utlist.h"
#include "pdu.h"
-#ifndef ARDUINO
+#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
static OCResourceHandle deviceResource = {0};
#ifdef WITH_PRESENCE
static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
-static PresenceResource presenceResource;
+static PresenceResource presenceResource = {0};
static uint8_t PresenceTimeOutSize = 0;
static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
#endif
static const char COAP_TCP[] = "coap+tcp:";
static const char CORESPEC[] = "core";
-//#ifdef DIRECT_PAIRING
-OCDirectPairingCB gDirectpairingCallback = NULL;
-//#endif
-
//-----------------------------------------------------------------------------
// Macros
//-----------------------------------------------------------------------------
*/
static void incrementSequenceNumber(OCResource * resPtr);
-/**
- * Verify the lengths of the URI and the query separately.
- *
- * @param inputUri Input URI and query.
- * @param uriLen The length of the initial URI with query.
- * @return ::OC_STACK_OK on success, some other value upon failure.
- */
-static OCStackResult verifyUriQueryLength(const char * inputUri,
- uint16_t uriLen);
-
/*
* Attempts to initialize every network interface that the CA Layer might have compiled in.
*
out->flags = CAToOCTransportFlags(in->flags);
OICStrcpy(out->addr, sizeof(out->addr), in->addr);
out->port = in->port;
- out->interface = in->interface;
+ out->ifindex = in->ifindex;
#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
memcpy(out->routeData, in->routeData, sizeof(out->routeData));
#endif
memcpy(out->routeData, in->routeData, sizeof(out->routeData));
#endif
out->port = in->port;
- out->interface = in->interface;
+ out->ifindex = in->ifindex;
}
void FixUpClientResponse(OCClientResponse *cr)
NULL, PAYLOAD_TYPE_REPRESENTATION,
NULL, 0, 0, NULL,
OC_OBSERVE_DEREGISTER,
- observer->observeId);
+ observer->observeId,
+ 0);
if(result != OC_STACK_OK)
{
return result;
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;
OCClientResponse response =
{.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
- response.sequenceNumber = OC_OBSERVE_NO_OPTION;
+ response.sequenceNumber = -1;
CopyEndpointToDevAddr(endPoint, &response.devAddr);
FixUpClientResponse(&response);
response.resourceUri = responseInfo->info.resourceUri;
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);
}
}
-OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
-{
- char *query;
-
- query = strchr (inputUri, '?');
-
- if (query != NULL)
- {
- if((query - inputUri) > MAX_URI_LENGTH)
- {
- return OC_STACK_INVALID_URI;
- }
-
- if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
- {
- return OC_STACK_INVALID_QUERY;
- }
- }
- else if(uriLen > MAX_URI_LENGTH)
- {
- return OC_STACK_INVALID_URI;
- }
- return OC_STACK_OK;
-}
-
/**
* A request uri consists of the following components in order:
* example
requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
}
- if (result != OC_STACK_OK)
- {
- OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
- goto exit;
- }
-
// prepare for response
#ifdef WITH_PRESENCE
if (method == OC_REST_PRESENCE)
{
return OC_STACK_INVALID_PARAM;
}
- deleteResourceType(resource->rsrcType);
- resource->rsrcType = NULL;
while (type)
{
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");
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
#endif // WITH_PRESENCE
pointer = temp;
}
+ memset(&platformResource, 0, sizeof(platformResource));
+ memset(&deviceResource, 0, sizeof(deviceResource));
SRMDeInitSecureResources();
// Ensure that the last resource to be deleted is the presence resource. This allows for all
// presence notification attributed to their deletion to be processed.
deleteResource((OCResource *) presenceResource.handle);
+ memset(&presenceResource, 0, sizeof(presenceResource));
#endif // WITH_PRESENCE
}
previous = pointer;
pointer = pointer->next;
}
- previous->next = newInterface;
+
+ if (previous)
+ {
+ previous->next = newInterface;
+ }
}
}
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;
+ }
+}
#include "logger.h"
#include "timer.h"
-#ifndef WITH_ARDUINO
-#include <pthread.h>
-#endif
+#include "platform_features.h"
#define TAG "OIC_RI_GROUP"
pointer = NULL; \
}
-#ifndef WITH_ARDUINO
-pthread_mutex_t lock;
+// Mutex implementation macros
+#if defined(HAVE_PTHREAD_H)
+
+ #include <pthread.h>
+ pthread_mutex_t lock;
+ #define MUTEX_LOCK(ARG_NAME) { pthread_mutex_lock(ARG_NAME); }
+ #define MUTEX_UNLOCK(ARG_NAME) { pthread_mutex_unlock(ARG_NAME); }
+
+#elif defined(HAVE_WINDOWS_H)
+
+ #include <windows.h>
+ CRITICAL_SECTION lock;
+ #define MUTEX_LOCK(ARG_NAME) { EnterCriticalSection(ARG_NAME); }
+ #define MUTEX_UNLOCK(ARG_NAME) { LeaveCriticalSection(ARG_NAME); }
+
+#elif defined(WITH_ARDUINO)
+
+ #define MUTEX_LOCK(ARG_NAME) { }
+ #define MUTEX_UNLOCK(ARG_NAME) { }
+
+#else
+
+ ERROR Need mutex implementation on this platform
+
#endif
enum ACTION_TYPE
{
OIC_LOG(INFO, TAG, "AddScheduledResource Entering...");
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+ MUTEX_LOCK(&lock);
ScheduledResourceInfo *tmp = NULL;
if (*head != NULL)
{
*head = add;
}
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+ MUTEX_UNLOCK(&lock);
}
ScheduledResourceInfo* GetScheduledResource(ScheduledResourceInfo *head)
{
OIC_LOG(INFO, TAG, "GetScheduledResource Entering...");
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+ MUTEX_LOCK(&lock);
time_t t_now;
ScheduledResourceInfo *tmp = NULL;
tmp = head;
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO)
time(&t_now);
#else
t_now = now();
while (tmp)
{
time_t diffTm = 0;
-#ifndef WITH_ARDUINO
diffTm = timespec_diff(tmp->time, t_now);
-#else
- diffTm = timespec_diff(tmp->time, t_now);
-#endif
if (diffTm <= (time_t) 0)
{
}
exit:
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+
+ MUTEX_UNLOCK(&lock);
+
if (tmp == NULL)
{
OIC_LOG(INFO, TAG, "Cannot Find Call Info.");
{
OIC_LOG(INFO, TAG, "GetScheduledResourceByActionSetName Entering...");
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+ MUTEX_LOCK(&lock);
+
ScheduledResourceInfo *tmp = NULL;
tmp = head;
}
exit:
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+
+ MUTEX_UNLOCK(&lock);
+
if (tmp == NULL)
{
OIC_LOG(INFO, TAG, "Cannot Find Call Info.");
void RemoveScheduledResource(ScheduledResourceInfo **head,
ScheduledResourceInfo* del)
{
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+
+ MUTEX_LOCK(&lock);
+
OIC_LOG(INFO, TAG, "RemoveScheduledResource Entering...");
ScheduledResourceInfo *tmp = NULL;
if (del == NULL)
{
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+
+ MUTEX_UNLOCK(&lock);
+
return;
}
}
OCFREE(del)
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+
+ MUTEX_UNLOCK(&lock);
+
}
typedef struct aggregatehandleinfo
// yyyy-mm-dd hh:mm:ss d
iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
VARIFY_PARAM_NULL(iterToken, result, exit)
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO)
if( 2 != sscanf(iterToken, "%ld %u", &(*set)->timesteps, &(*set)->type) )
{
// If the return value should be 2, the number of items in the argument. Otherwise, it fails.
OIC_LOG(INFO, TAG, "Target ActionSet is NULL");
goto exit;
}
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+
+ MUTEX_LOCK(&lock);
+
DoAction(info->resource, info->actionset, info->ehRequest);
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+
+ MUTEX_UNLOCK(&lock);
+
if (info->actionset->type == RECURSIVE)
{
if (info->actionset->timesteps > 0)
{
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+ MUTEX_LOCK(&lock);
schedule->resource = info->resource;
schedule->actionset = info->actionset;
schedule->ehRequest = info->ehRequest;
&DoScheduledGroupAction);
OIC_LOG(INFO, TAG, "Reregisteration.");
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+ MUTEX_UNLOCK(&lock);
AddScheduledResource(&scheduleResourceList, schedule);
}
else
char *doWhat = NULL;
char *details = NULL;
+#if defined(_WIN32)
+ static bool initializedCriticalSection = false;
+
+ if(false == initializedCriticalSection) {
+ /** @todo Find a way to DeleteCriticalSection somewhere. */
+ InitializeCriticalSection(&lock);
+ initializedCriticalSection = true;
+ }
+#endif
+
stackRet = ExtractKeyValueFromRequest(ehRequest, &doWhat, &details);
if(stackRet != OC_STACK_OK)
OIC_LOG(INFO, TAG, "Building New Call Info.");
memset(schedule, 0,
sizeof(ScheduledResourceInfo));
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+ MUTEX_LOCK(&lock);
schedule->resource = resource;
schedule->actionset = actionset;
schedule->ehRequest =
(OCServerRequest*) ehRequest->requestHandle;
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+ MUTEX_UNLOCK(&lock);
if (delay > 0)
{
OIC_LOG_V(INFO, TAG, "delay_time is %ld seconds.",
actionset->timesteps);
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+ MUTEX_LOCK(&lock);
schedule->time = registerTimer(delay,
&schedule->timer_id,
&DoScheduledGroupAction);
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+ MUTEX_UNLOCK(&lock);
AddScheduledResource(&scheduleResourceList,
schedule);
stackRet = OC_STACK_OK;
entry->timeStamp = OICGetCurrentTime(TIME_IN_US);
entry->remoteAddr.adapter = endpoint->adapter;
entry->remoteAddr.flags = endpoint->flags;
- entry->remoteAddr.interface = endpoint->interface;
+ entry->remoteAddr.ifindex = endpoint->ifindex;
entry->remoteAddr.port = endpoint->port;
strncpy(entry->remoteAddr.addr, endpoint->addr, sizeof(entry->remoteAddr.addr));
if (id)
{
OICStrcpy((char*)tags->di.id, MAX_IDENTITY_SIZE, (char *)id);
- if (!tags->di.id)
- {
- goto memory_allocation_failed;
- }
}
if (baseURI)
{
])
stacktest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
-stacktest_env.AppendUnique(LIBS = ['-lpthread'])
stacktest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
stacktest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs'])
-stacktest_env.PrependUnique(LIBS = ['m',
- 'octbstack',
+stacktest_env.PrependUnique(LIBS = ['octbstack',
'ocsrm',
'connectivity_abstraction',
'coap',
if env.get('LOGGING'):
stacktest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+if target_os in ['msys_nt', 'windows']:
+ stacktest_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE'])
+ stacktest_env.AppendUnique(LIBS = ['ws2_32', 'iphlpapi', 'kernel32'])
+else:
+ stacktest_env.PrependUnique(LIBS = ['m', 'pthread'])
+
######################################################################
# Source files and Targets
######################################################################
env.AppendTarget('test')
if env.get('TEST') == '1':
- target_os = env.get('TARGET_OS')
- if target_os == 'linux':
+ if target_os in ['windows']:
+ stacktest_env.AppendENVPath('PATH', [os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk')])
+ if target_os in ['linux', 'windows']:
from tools.scons.RunTest import *
run_test(stacktest_env,
'resource_csdk_stack_test.memcheck',
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
#include <stdlib.h>
//-----------------------------------------------------------------------------
extern "C"
{
+ #include "ocpayload.h"
#include "ocstack.h"
#include "ocstackinternal.h"
#include "logger.h"
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
#include <stdlib.h>
//-----------------------------------------------------------------------------
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,
EXPECT_EQ(OC_STACK_OK, OCStop());
}
+TEST(StackStart, StackStartSuccessServerThenClient)
+{
+ itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+ EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER));
+ EXPECT_EQ(OC_STACK_OK, OCStop());
+ EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT));
+ EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
+TEST(StackStart, StackStartSuccessClientThenServer)
+{
+ itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+ EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT));
+ EXPECT_EQ(OC_STACK_OK, OCStop());
+ EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER));
+ EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
TEST(StackStart, StackStartSuccessiveInits)
{
itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
EXPECT_EQ(OC_STACK_OK, OCStop());
}
+// Visual Studio versions earlier than 2015 have bugs in is_pod and report the wrong answer.
+#if !defined(_MSC_VER) || (_MSC_VER >= 1900)
TEST(PODTests, OCHeaderOption)
{
EXPECT_TRUE(std::is_pod<OCHeaderOption>::value);
TEST(PODTests, OCCallbackData)
{
- EXPECT_TRUE(std::is_pod<OCHeaderOption>::value);
+ EXPECT_TRUE(std::is_pod<OCCallbackData>::value);
}
+#endif
TEST(OCDoDirectPairingTests, Nullpeer)
{
- EXPECT_EQ(OC_STACK_INVALID_PARAM,OCDoDirectPairing(NULL, pmSel, &pinNumber, &resultCallback));
+ EXPECT_EQ(OC_STACK_INVALID_PARAM,OCDoDirectPairing(NULL, NULL, pmSel, &pinNumber, &resultCallback));
}
TEST(OCDoDirectPairingTests, NullCallback)
{
- EXPECT_EQ(OC_STACK_INVALID_CALLBACK,OCDoDirectPairing(&peer, pmSel, &pinNumber, NULL));
+ EXPECT_EQ(OC_STACK_INVALID_CALLBACK,OCDoDirectPairing(NULL, &peer, pmSel, &pinNumber, NULL));
}
TEST(OCDoDirectPairingTests, NullpinNumber)
{
- EXPECT_EQ(OC_STACK_INVALID_PARAM,OCDoDirectPairing(&peer, pmSel, NULL, &resultCallback));
+ EXPECT_EQ(OC_STACK_INVALID_PARAM,OCDoDirectPairing(NULL, &peer, pmSel, NULL, &resultCallback));
}
TEST(StackResource, MultipleResourcesDiscovery)
EXPECT_EQ(OC_STACK_OK, OCStop());
}
+
+TEST(StackPayload, CloneByteString)
+{
+ uint8_t bytes[] = { 0, 1, 2, 3 };
+ OCByteString byteString;
+ byteString.bytes = bytes;
+ byteString.len = sizeof(bytes);
+
+ OCRepPayload *original = OCRepPayloadCreate();
+ ASSERT_TRUE(original != NULL);
+ EXPECT_TRUE(OCRepPayloadSetPropByteString(original, "name", byteString));
+
+ OCRepPayload *clone = OCRepPayloadClone(original);
+ ASSERT_TRUE(clone != NULL);
+
+ OCRepPayloadDestroy(original);
+
+ OCByteString cloneByteString;
+ EXPECT_TRUE(OCRepPayloadGetPropByteString(clone, "name", &cloneByteString));
+ ASSERT_TRUE(cloneByteString.bytes != NULL);
+ EXPECT_EQ(sizeof(bytes), cloneByteString.len);
+ EXPECT_TRUE(0 == memcmp(bytes, cloneByteString.bytes, sizeof(bytes)));
+ OICFree(cloneByteString.bytes);
+
+ OCRepPayloadDestroy(clone);
+}
])
target_os = env.get('TARGET_OS')
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
examples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
# Note: 'pthread' is in libc for android. On other platform, if use
examples_env.AppendUnique(LIBS = ['octbstack'])
examples_env.AppendUnique(LIBS = ['oc'])
+if target_os in ['msys_nt', 'windows']:
+ examples_env.PrependUnique(LIBS = ['mswsock', 'ws2_32', 'iphlpapi', 'ole32'])
+
if env.get('SECURED') == '1':
- examples_env.AppendUnique(LIBS = ['tinydtls'])
+ examples_env.AppendUnique(LIBS = ['tinydtls'])
+ examples_env.AppendUnique(CPPDEFINES = ['_WITH_DTLS_'])
+ if target_os in ['msys_nt', 'windows']:
+ examples_env.AppendUnique(LIBS = ['advapi32'])
if target_os == 'android':
examples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
if target_os in ['darwin', 'ios']:
examples_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
+if env.get('LOGGING'):
+ examples_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+if target_os in ['msys_nt', 'windows']:
+ examples_env.AppendUnique(LIBS = ['Comctl32', 'Gdi32', 'User32'])
+
+if env.get('LOGGING'):
+ examples_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+def make_single_file_cpp_program(program_name):
+ return examples_env.Program(program_name, program_name + ".cpp")
+
######################################################################
# Source files and Targets
######################################################################
-simpleserver = examples_env.Program('simpleserver', 'simpleserver.cpp')
-simpleclient = examples_env.Program('simpleclient', 'simpleclient.cpp')
-simpleserverHQ = examples_env.Program('simpleserverHQ', 'simpleserverHQ.cpp')
-simpleclientHQ = examples_env.Program('simpleclientHQ', 'simpleclientHQ.cpp')
-fridgeserver = examples_env.Program('fridgeserver', 'fridgeserver.cpp')
-fridgeclient = examples_env.Program('fridgeclient', 'fridgeclient.cpp')
-presenceserver = examples_env.Program('presenceserver', 'presenceserver.cpp')
-presenceclient = examples_env.Program('presenceclient', 'presenceclient.cpp')
-simpleclientserver = examples_env.Program('simpleclientserver', 'simpleclientserver.cpp')
-roomserver = examples_env.Program('roomserver', 'roomserver.cpp')
-roomclient = examples_env.Program('roomclient', 'roomclient.cpp')
-garageserver = examples_env.Program('garageserver', 'garageserver.cpp')
-garageclient = examples_env.Program('garageclient', 'garageclient.cpp')
-groupserver = examples_env.Program('groupserver', 'groupserver.cpp')
-groupclient = examples_env.Program('groupclient', 'groupclient.cpp')
-lightserver = examples_env.Program('lightserver', 'lightserver.cpp')
-devicediscoveryserver = examples_env.Program('devicediscoveryserver', 'devicediscoveryserver.cpp')
-devicediscoveryclient = examples_env.Program('devicediscoveryclient', 'devicediscoveryclient.cpp')
-threadingsample = examples_env.Program('threadingsample', 'threadingsample.cpp')
+example_names = [
+ 'simpleserver', 'simpleclient',
+ 'simpleclientserver',
+ 'directpairingclient',
+ 'devicediscoveryserver', 'devicediscoveryclient'
+ ]
+
+if target_os not in ['windows', 'msys_nt']:
+ example_names += [
+ 'simpleserverHQ', 'simpleclientHQ',
+ 'fridgeserver', 'fridgeclient',
+ 'presenceserver', 'presenceclient',
+ 'roomserver', 'roomclient',
+ 'garageserver',
+ 'garageclient',
+ 'groupserver',
+ 'groupclient',
+ 'lightserver',
+ 'threadingsample',
+ ]
+examples = map(make_single_file_cpp_program, example_names)
+
+######################################################################
+# Other examples
+######################################################################
clientjson = examples_env.Install(env.get('BUILD_DIR') + '/resource/examples/',
env.get('SRC_DIR') + '/resource/examples/' + 'oic_svr_db_client.dat')
serverjson = examples_env.Install(env.get('BUILD_DIR') + '/resource/examples/',
env.get('SRC_DIR') + '/resource/examples/' + 'oic_svr_db_server.dat')
-Alias("examples", [simpleserver, simpleclient,
- simpleserverHQ, simpleclientHQ,
- fridgeserver, fridgeclient,
- presenceserver, presenceclient,
- simpleclientserver, roomserver, roomclient, garageserver,
- garageclient,
- groupserver, groupclient,
- lightserver,
- devicediscoveryserver, devicediscoveryclient,
- threadingsample,
- serverjson, clientjson
- ])
+directpairingdat = examples_env.Install(env.get('BUILD_DIR') + '/resource/examples/',
+ env.get('SRC_DIR') + '/resource/examples/' + 'oic_svr_db_client_directpairing.dat')
+
+examples += [clientjson, serverjson, directpairingdat]
+
+if target_os in ['msys_nt', 'windows']:
+ winUIClient = examples_env.Program('winUIClient', ['winuiclientgui.cpp', 'winuiclient.cpp'])
+ mediaserver = examples_env.Program('mediaserver', 'mediaserver.cpp')
+ examples += [winUIClient, mediaserver]
+
+Alias("examples", examples)
env.AppendTarget('examples')
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";
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;
void DeleteDeviceInfo()
{
delete[] deviceInfo.deviceName;
+ delete[] deviceInfo.specVersion;
+ OCFreeOCStringLL(deviceInfo.dataModelVersions);
}
void DuplicateString(char ** targetString, std::string sourceString)
}
-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;
}
}
- result = SetDeviceInfo(deviceName);
+ result = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.wk.d");
OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.d.tv");
--- /dev/null
+/* *****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * *****************************************************************/
+
+#include <stdio.h>
+#include <string.h>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <string>
+#include <map>
+#include <cstdlib>
+#include <mutex>
+#include <condition_variable>
+
+#include "logger.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+#define MAX_URI_LENGTH (64)
+#define MAX_PERMISSION_LENGTH (5)
+#define CREATE (1)
+#define READ (2)
+#define UPDATE (4)
+#define DELETE (8)
+#define NOTIFY (16)
+#define DASH '-'
+#define PREDEFINED_TIMEOUT (10)
+#define MAX_OWNED_DEVICE (10)
+#define TAG "provisioningclient"
+
+#define JSON_DB_PATH "./oic_svr_db_client.json"
+#define DAT_DB_PATH "./oic_svr_db_client.dat"
+#define DEV_STATUS_ON "DEV_STATUS_ON"
+#define DEV_STATUS_OFF "DEV_STATUS_OFF"
+
+#define DP_DISCOVERY_TIMEOUT 4
+#define DP_PIN_LENGTH 8
+
+#define BOLD_BEGIN "\033[1m"
+#define RED_BEGIN "\033[1;31m"
+#define GREEN_BEGIN "\033[1;92m"
+#define COLOR_END "\033[0m"
+
+using namespace OC;
+
+static int ask = 1;
+static PairedDevices discoveredDeviceList, pairedDeviceList;
+
+static FILE* client_open(const char* /*fileName*/, const char *mode)
+{
+ return fopen(DAT_DB_PATH, mode);
+}
+
+
+static void printMenu()
+{
+ std::cout << GREEN_BEGIN "Choose an option:" COLOR_END<<std::endl;
+ std::cout << GREEN_BEGIN "# 1 (DP device discovery) : discover Direct-Pairing devices"
+ COLOR_END<<std::endl;
+ std::cout << GREEN_BEGIN "# 2 (start Direct-Pairing) : negotiate DP method & start Direct-Pairin"
+ COLOR_END<<std::endl;
+ std::cout << GREEN_BEGIN "# 3 (list all device) : list all discovered/paired devices"
+ COLOR_END<<std::endl;
+ std::cout << GREEN_BEGIN "# 4 (send data) : send data to device" COLOR_END<<std::endl;
+ std::cout << GREEN_BEGIN "# 9 (quit) : quit test " COLOR_END<<std::endl;
+}
+
+static void printPrompt()
+{
+ std::cout << BOLD_BEGIN "IoTivity-DP#" COLOR_END" ";
+}
+
+static void printDevices(PairedDevices& list)
+{
+ for (size_t i = 0; i < list.size(); i++)
+ {
+ std::cout << "["<< i+1 << "]" << " ID: " << list[i]->getDeviceID() << std::endl;
+ }
+}
+
+static void findCallback(PairedDevices discoveredDevList)
+{
+
+ if (0 == discoveredDevList.size())
+ {
+ std::cout<< "No Direct-pairing Support device Found" << std::endl;
+ }
+ else
+ {
+ std::cout << "Discovered Direct-Pairing Support Device"<< std::endl;
+ discoveredDeviceList = discoveredDevList;
+ printDevices(discoveredDevList);
+ }
+
+ printMenu();
+ printPrompt();
+ fflush(NULL);
+}
+
+static bool printPairingMethod(int choice)
+{
+ if (NULL == discoveredDeviceList[choice])// || false == discoveredDeviceList[choice]->edp)
+ {
+ std::cout<< "Invalid device or Not support direct-pairing..\n\n" << std::endl;
+ return false;
+ }
+
+ auto prms = discoveredDeviceList[choice]->getPairingMethods();
+ if (0 == prms.size())
+ {
+ std::cout << "Not exist any support method..\n\n" << std::endl;
+ return false;
+ }
+
+ bool ret = true;
+ std::cout << "\n* List of supported pairing methods *" << std::endl;
+
+ for (unsigned int i = 0; i < prms.size(); i++)
+ {
+ std::cout<< "[" << i+1 << "]";
+ switch (prms[i])
+ {
+ case DP_PRE_CONFIGURED:
+ std::cout<<"Pre-Configured PIN"<<std::endl;;
+ break;
+ case DP_RANDOM_PIN:
+ std::cout<<"Random PIN"<<std::endl;;
+ break;
+ default:
+ std::cout<<"NOT Allowed ("<< prms[i]<<")"<<std::endl;
+ ret = false;
+ break;
+ }
+ std::cout<<std::endl;
+ }
+
+ return ret;
+}
+
+static void resultCallback(std::shared_ptr<OCDirectPairing> ptr, OCStackResult result)
+{
+
+ if (OC_STACK_OK == result)
+ {
+ std::cout << " Direct-Pairing SUCCESS" << std::endl;
+ std::cout << "Taget Add info:" << ptr->getHost() << std::endl;
+ }
+ else {
+ std::cout <<" Direct-Pairing FAILED" << std::endl;
+ }
+
+ printMenu();
+ printPrompt();
+ fflush(NULL);
+}
+
+static void pairedDevListCB(PairedDevices pairedDevList)
+{
+
+ if (0 == pairedDevList.size())
+ {
+ std::cout << "No Paired Devcie Found" << std::endl;
+ }
+ else
+ {
+ pairedDeviceList = pairedDevList;
+ printDevices(pairedDevList);
+ }
+
+ printMenu();
+ printPrompt();
+ fflush(NULL);
+}
+
+static void getCallback(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+{
+ (void)(headerOptions);
+ try
+ {
+ if (OC_STACK_OK == eCode)
+ {
+ std::cout << "Callback Context for GET query recvd successfully" << std::endl;
+ std::cout << "Resource URI: " << rep.getUri() << std::endl;
+
+ bool state = false;
+ int power = 0;
+ rep.getValue("state", state);
+ rep.getValue("power", power);
+
+ std::cout << "\tstate: " << state << std::endl;
+ std::cout << "\tpower: " << power << std::endl;
+ }
+ else
+ {
+ std::cout << "getCallback Response error: " << eCode << std::endl;
+ }
+ }
+ catch(std::exception& e)
+ {
+ std::cout << "Exception: " << e.what() << " in onGet" << std::endl;
+ }
+}
+
+static bool InputPIN(std::string& pin)
+{
+ std::cout <<" > Enter PIN Number for authentication (ex - '00000000' [8 digit] ):" ;
+
+ std::cin >> pin;
+
+ if (pin.size() != DP_PIN_LENGTH)
+ {
+ std::cout<<"Invalid PIN"<<std::endl;
+ return false;
+ }
+
+ return true;
+}
+
+int main(void)
+{
+ OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
+
+ // Create PlatformConfig object
+ PlatformConfig cfg {
+ OC::ServiceType::InProc,
+ OC::ModeType::Both,
+ "0.0.0.0",
+ 0,
+ OC::QualityOfService::LowQos,
+ &ps
+ };
+
+ OCPlatform::Configure(cfg);
+
+ try
+ {
+ unsigned int choice;
+ for (int out = 0; !out;)
+ {
+ if (ask)
+ {
+ printMenu();
+ printPrompt();
+ fflush(NULL);
+ }
+ std::cin >> choice;
+
+ switch(choice) {
+ case 1:
+ {
+ OCStackResult result = OC::OCPlatform::findDirectPairingDevices(
+ DP_DISCOVERY_TIMEOUT, findCallback);
+
+ if (OC_STACK_NO_RESOURCE == result)
+ {
+ std::cout << "!! No Direct-Pairing Support Device found"<<std::endl;
+ break;
+ }
+
+ if (OC_STACK_OK != result)
+ {
+ std::cout << "!!Error - findDirectPairingDevices failed."<<std::endl;
+ }
+ ask = 0;
+ break;
+ }
+ case 2:
+ {
+ unsigned int pMethodIDx = -1;
+ std::string pin("");
+
+ std::cout << "- Negotiate DP method & Start Direct-Pairing - ";
+ std::cout << "* List of discovered device" << std::endl;
+ printDevices(discoveredDeviceList);
+ std::cout << " > Enter Peer Device Number to initiate Direct-Pairing:" << std::endl;
+ printPrompt();
+ std::cin >> choice;
+ if (choice < 1 || choice > discoveredDeviceList.size())
+ {
+ std::cout << "!!Device Number is incorrect, Try Again" << std::endl;
+ break;
+ }
+ OCPrm_t pmSel = DP_NOT_ALLOWED;
+ choice--;
+ if (false == printPairingMethod(choice))
+ {
+ std::cout << "Target does not support the Direct-Pairing" << std::endl;
+ break;
+ }
+
+ std::cout << " > Enter pairing method: "<< std::endl;
+ printPrompt();
+ std::cin >> pMethodIDx;
+ auto prms = discoveredDeviceList[choice]->getPairingMethods();
+ if (0 >= pMethodIDx || prms.size() < pMethodIDx)
+ {
+ std::cout <<"Invalid mode selection" << std::endl;
+ break;
+ }
+
+ pmSel = prms[pMethodIDx - 1];
+ if (false == InputPIN(pin))
+ {
+ break;
+ }
+
+ OCStackResult result = OC::OCPlatform::doDirectPairing(discoveredDeviceList[choice], pmSel, pin, resultCallback);
+
+ if (OC_STACK_OK != result)
+ {
+ std::cout << "!!Error - doDirectPairing failed." << std::endl;
+ }
+ ask = 0;
+ break;
+ }
+ case 3:
+ {
+ std::cout << "- List all discovered and paired devices) -";
+ std::cout << " > List of discovered devices" << std::endl;
+ printDevices(discoveredDeviceList);
+ std::cout << std::endl;
+
+ std::cout << " > List of paired devices" << std::endl;
+ OCStackResult result = OC::OCPlatform::getDirectPairedDevices(pairedDevListCB);
+ printDevices(pairedDeviceList);
+ std::cout << std::endl;
+
+ if (OC_STACK_NO_RESOURCE == result)
+ {
+ std::cout << "!! No Paired device found"<<std::endl;
+ break;
+ }
+ if (OC_STACK_OK != result)
+ {
+ std::cout << "!!Error - getDirectPairedDevices failed."<<std::endl;
+ }
+ break;
+ }
+ case 4:
+ {
+ std::cout << "- Send data(GET Request) to device(led server) -" << std::endl;
+ printDevices(pairedDeviceList);
+ pairedDeviceList = discoveredDeviceList;
+ printMenu();
+ std::cout << "Enter device number to GET data: ";
+ std::cin >> choice;
+ choice--;
+
+ std::vector<std::string> ledTypes = {"core.led"};
+ std::vector<std::string> ifaces = {DEFAULT_INTERFACE};
+
+ OCConnectivityType ct = pairedDeviceList[choice]->getConnType();
+
+ std::cout << "\n\n HOST address is : " << pairedDeviceList[choice]->getHost() << "\n\n";
+ OCResource::Ptr led = OC::OCPlatform::constructResourceObject(
+ pairedDeviceList[choice]->getHost(),
+ "/a/led", ct, false, ledTypes, ifaces);
+
+ if(!led)
+ {
+ std::cout << "Error: Led Object construction returned null" << std::endl;
+ break;
+ }
+ OCStackResult res = led->get(QueryParamsMap(), getCallback);
+
+ if (OC_STACK_OK != res)
+ {
+ std::cout << "Error: get Failed for Led" << std::endl;
+ }
+ break;
+ }
+ case 9:
+ {
+ out = 1;
+ break;
+ }
+ default:
+ {
+ std::cout << GREEN_BEGIN "Wrong Option : Try Again" COLOR_END << std::endl;
+ printMenu();
+ printPrompt();
+ break;
+ }
+ }
+ }
+ }
+ catch(OCException& e)
+ {
+ oclog() << "Exception in main: "<< e.what();
+ }
+
+ return 0;
+}
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)
{
/// (properties and methods) and host this resource on the server.
///
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
#include <functional>
#include <pthread.h>
--- /dev/null
+/* ****************************************************************
+ *
+ * Copyright 2016 Intel Corporation All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+///
+/// This sample provides steps to define an interface for a resource
+/// (properties and methods) and host this resource on the server.
+///
+
+#include <functional>
+#include <mutex>
+#include "platform_features.h"
+#include <condition_variable>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include <windows.h>
+#include <objbase.h>
+
+#include <commctrl.h>
+#include <mmdeviceapi.h>
+#include <endpointvolume.h>
+#include <stdio.h>
+#include <math.h> /* log */
+
+#define SAFE_RELEASE(x) \
+ if ((x) != NULL) \
+ { (x)->Release(); (x) = NULL; }
+
+using namespace OC;
+using namespace std;
+namespace PH = std::placeholders;
+
+int gObservation = 0;
+void * ChangeMediaRepresentation (void *param);
+void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest);
+void playPause(void);
+void setVolume(int vol);
+int getVolume(void);
+
+// Specifies where to notify all observers or list of observers
+// false: notifies all observers
+// true: notifies list of observers
+bool isListOfObservers = false;
+
+// Specifies secure or non-secure
+// false: non-secure resource
+// true: secure resource
+bool isSecure = false;
+
+/// Specifies whether Entity handler is going to do slow response or not
+bool isSlowResponse = false;
+
+
+// Forward declaring the entityHandler
+
+/// This class represents a single resource named 'MediaResource'. This resource has
+/// two simple properties named 'state' and 'volume'
+
+class MediaResource
+{
+
+public:
+ /// Access this property from a TB client
+ std::string m_name;
+ bool m_state;
+ int m_volume;
+ std::string m_mediaUri;
+ OCResourceHandle m_resourceHandle;
+ OCRepresentation m_mediaRep;
+ ObservationIds m_interestedObservers;
+
+public:
+ /// Constructor
+ MediaResource()
+ :m_name("Media Player"), m_state(false), m_volume(0), m_mediaUri("/a/media"),
+ m_resourceHandle(nullptr)
+ {
+ // Initialize representation
+ m_mediaRep.setUri(m_mediaUri);
+
+ m_mediaRep.setValue("state", m_state);
+ m_mediaRep.setValue("volume", m_volume);
+ m_mediaRep.setValue("name", m_name);
+ }
+
+ /* Note that this does not need to be a member function: for classes you do not have
+ access to, you can accomplish this with a free function: */
+
+ /// This function internally calls registerResource API.
+ void createResource()
+ {
+ //URI of the resource
+ std::string resourceURI = m_mediaUri;
+ //resource type name. In this case, it is media
+ std::string resourceTypeName = "core.media";
+ // resource interface.
+ std::string resourceInterface = DEFAULT_INTERFACE;
+
+ // OCResourceProperty is defined ocstack.h
+ uint8_t resourceProperty;
+ if(isSecure)
+ {
+ resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE;
+ }
+ else
+ {
+ resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
+ }
+ EntityHandler cb = std::bind(&MediaResource::entityHandler, this,PH::_1);
+
+ // This will internally create and register the resource.
+ OCStackResult result = OCPlatform::registerResource(
+ m_resourceHandle, resourceURI, resourceTypeName,
+ resourceInterface, cb, resourceProperty);
+
+ if (OC_STACK_OK != result)
+ {
+ cout << "Resource creation was unsuccessful\n";
+ }
+ }
+
+ OCResourceHandle getHandle()
+ {
+ return m_resourceHandle;
+ }
+
+ // Puts representation.
+ // Gets values from the representation and
+ // updates the internal state
+ void put(OCRepresentation& rep)
+ {
+ try
+ {
+ if (rep.getValue("state", m_state))
+ {
+ cout << "\t\t\t\t" << "state: " << m_state << endl;
+ if(m_state)
+ {
+ playPause();
+ }
+ }
+ else
+ {
+ cout << "\t\t\t\t" << "state not found in the representation" << endl;
+ }
+
+ if (rep.getValue("volume", m_volume))
+ {
+ cout << "\t\t\t\t" << "volume: " << m_volume << endl;
+ if((0 <= m_volume) && (m_volume <= 100))
+ {
+ setVolume(m_volume);
+ }
+ }
+ else
+ {
+ cout << "\t\t\t\t" << "volume not found in the representation" << endl;
+ }
+ }
+ catch (exception& e)
+ {
+ cout << e.what() << endl;
+ }
+
+ }
+
+ // Post representation.
+ // Post can create new resource or simply act like put.
+ // Gets values from the representation and
+ // updates the internal state
+ OCRepresentation post(OCRepresentation& rep)
+ {
+ put(rep);
+ return get();
+ }
+
+
+ // gets the updated representation.
+ // Updates the representation with latest internal state before
+ // sending out.
+ OCRepresentation get()
+ {
+ m_mediaRep.setValue("state", m_state);
+ m_mediaRep.setValue("volume", m_volume);
+
+ return m_mediaRep;
+ }
+
+ void addType(const std::string& type) const
+ {
+ OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
+ if (OC_STACK_OK != result)
+ {
+ cout << "Binding TypeName to Resource was unsuccessful\n";
+ }
+ }
+
+ void addInterface(const std::string& intf) const
+ {
+ OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, intf);
+ if (OC_STACK_OK != result)
+ {
+ cout << "Binding TypeName to Resource was unsuccessful\n";
+ }
+ }
+
+private:
+// This is just a sample implementation of entity handler.
+// Entity handler can be implemented in several ways by the manufacturer
+OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
+{
+ cout << "\tIn Server CPP entity handler:\n";
+ OCEntityHandlerResult ehResult = OC_EH_ERROR;
+ if(request)
+ {
+ // Get the request type and request flag
+ std::string requestType = request->getRequestType();
+ int requestFlag = request->getRequestHandlerFlag();
+
+ if(requestFlag & RequestHandlerFlag::RequestFlag)
+ {
+ cout << "\t\trequestFlag : Request\n";
+ auto pResponse = std::make_shared<OC::OCResourceResponse>();
+ pResponse->setRequestHandle(request->getRequestHandle());
+ pResponse->setResourceHandle(request->getResourceHandle());
+
+ // Check for query params (if any)
+ QueryParamsMap queries = request->getQueryParameters();
+
+ if (!queries.empty())
+ {
+ cout << "\nQuery processing upto entityHandler" << std::endl;
+ }
+ for (auto it : queries)
+ {
+ cout << "Query key: " << it.first << " value : " << it.second
+ << std::endl;
+ }
+
+ // If the request type is GET
+ if(requestType == "GET")
+ {
+ cout << "\t\t\trequestType : GET\n";
+ if(isSlowResponse) // Slow response case
+ {
+ static int startedThread = 0;
+ if(!startedThread)
+ {
+ std::thread t(handleSlowResponse, (void *)this, request);
+ startedThread = 1;
+ t.detach();
+ }
+ ehResult = OC_EH_SLOW;
+ }
+ else // normal response case.
+ {
+ pResponse->setErrorCode(200);
+ pResponse->setResponseResult(OC_EH_OK);
+ pResponse->setResourceRepresentation(get());
+ if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+ {
+ ehResult = OC_EH_OK;
+ }
+ }
+ }
+ else if(requestType == "PUT")
+ {
+ cout << "\t\t\trequestType : PUT\n";
+ OCRepresentation rep = request->getResourceRepresentation();
+
+ // Do related operations related to PUT request
+ // Update the mediaResource
+ put(rep);
+ pResponse->setErrorCode(200);
+ pResponse->setResponseResult(OC_EH_OK);
+ pResponse->setResourceRepresentation(get());
+ if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+ {
+ ehResult = OC_EH_OK;
+ }
+ }
+ else if(requestType == "POST")
+ {
+ cout << "\t\t\trequestType : POST\n";
+
+ OCRepresentation rep = request->getResourceRepresentation();
+
+ // Do related operations related to POST request
+ OCRepresentation rep_post = post(rep);
+ pResponse->setResourceRepresentation(rep_post);
+ pResponse->setErrorCode(200);
+ if(rep_post.hasAttribute("createduri"))
+ {
+ pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
+ pResponse->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
+ }
+ else
+ {
+ pResponse->setResponseResult(OC_EH_OK);
+ }
+
+ if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+ {
+ ehResult = OC_EH_OK;
+ }
+ }
+ else if(requestType == "DELETE")
+ {
+ cout << "Delete request received" << endl;
+ }
+ }
+
+ if(requestFlag & RequestHandlerFlag::ObserverFlag)
+ {
+ ObservationInfo observationInfo = request->getObservationInfo();
+ if(ObserveAction::ObserveRegister == observationInfo.action)
+ {
+ m_interestedObservers.push_back(observationInfo.obsId);
+ }
+ else if(ObserveAction::ObserveUnregister == observationInfo.action)
+ {
+ m_interestedObservers.erase(std::remove(
+ m_interestedObservers.begin(),
+ m_interestedObservers.end(),
+ observationInfo.obsId),
+ m_interestedObservers.end());
+ }
+
+ cout << "\t\trequestFlag : Observer\n";
+ gObservation = 1;
+ static int startedThread = 0;
+
+ // Observation happens on a different thread in ChangeMediaRepresentation function.
+ // If we have not created the thread already, we will create one here.
+
+ if(!startedThread)
+ {
+ std::thread t(ChangeMediaRepresentation, (void *)this);
+ startedThread = 1;
+ t.detach();
+ }
+
+ ehResult = OC_EH_OK;
+ }
+ }
+ else
+ {
+ cout << "Request invalid" << std::endl;
+ }
+
+ return ehResult;
+}
+
+};
+
+// ChangeMediaRepresentaion is an observation function,
+// which notifies any changes to the resource to stack
+// via notifyObservers
+void * ChangeMediaRepresentation (void *param)
+{
+ int prevVolume = 0;
+ MediaResource* mediaPtr = (MediaResource*) param;
+
+ // This function continuously monitors for the changes
+ while (1)
+ {
+ Sleep(100);
+
+ if (gObservation)
+ {
+ prevVolume = mediaPtr->m_volume;
+ mediaPtr->m_volume = getVolume();
+ if (prevVolume == mediaPtr->m_volume)
+ continue;
+
+ cout << "Volume changed from " << prevVolume << "% to " << mediaPtr->m_volume << "%\n";
+
+ // If under observation if there are any changes to the media resource
+ // we call notifyObservors
+ //
+ // For demostration we are changing the volume value and notifying.
+
+ cout << "\nVolume updated to : " << mediaPtr->m_volume << endl;
+ cout << "Notifying observers with resource handle: " << mediaPtr->getHandle() << endl;
+
+ OCStackResult result = OC_STACK_OK;
+
+ if(isListOfObservers)
+ {
+ std::shared_ptr<OCResourceResponse> resourceResponse =
+ {std::make_shared<OCResourceResponse>()};
+
+ resourceResponse->setErrorCode(200);
+ resourceResponse->setResourceRepresentation(mediaPtr->get(), DEFAULT_INTERFACE);
+
+ result = OCPlatform::notifyListOfObservers( mediaPtr->getHandle(),
+ mediaPtr->m_interestedObservers,
+ resourceResponse);
+ }
+ else
+ {
+ result = OCPlatform::notifyAllObservers(mediaPtr->getHandle());
+ }
+
+ if(OC_STACK_NO_OBSERVERS == result)
+ {
+ cout << "No More observers, stopping notifications" << endl;
+ gObservation = 0;
+ }
+ }
+ }
+
+ return NULL;
+}
+
+void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest)
+{
+ // This function handles slow response case
+ MediaResource* mediaPtr = (MediaResource*) param;
+ // Induce a case for slow response by using sleep
+ cout << "SLOW response" << std::endl;
+ sleep (10);
+
+ auto pResponse = std::make_shared<OC::OCResourceResponse>();
+ pResponse->setRequestHandle(pRequest->getRequestHandle());
+ pResponse->setResourceHandle(pRequest->getResourceHandle());
+ pResponse->setResourceRepresentation(mediaPtr->get());
+ pResponse->setErrorCode(200);
+ pResponse->setResponseResult(OC_EH_OK);
+
+ // Set the slow response flag back to false
+ isSlowResponse = false;
+ OCPlatform::sendResponse(pResponse);
+ return NULL;
+}
+
+void PrintUsage()
+{
+ cout << std::endl;
+ cout << "Usage : mediaserver <value>\n";
+ cout << " Default - Non-secure resource and notify all observers\n";
+ cout << " 1 - Non-secure resource and notify list of observers\n\n";
+ cout << " 2 - Secure resource and notify all observers\n";
+ cout << " 3 - Secure resource and notify list of observers\n\n";
+ cout << " 4 - Non-secure resource, GET slow response, notify all observers\n";
+}
+
+static FILE* client_open(const char* /*path*/, const char *mode)
+{
+ return fopen("./oic_svr_db_server.json", mode);
+}
+
+void playPause()
+{
+ INPUT ip;
+
+ // Set up a generic keyboard event.
+ ip.type = INPUT_KEYBOARD;
+ ip.ki.wScan = 0; // hardware scan code for key
+ ip.ki.time = 0;
+ ip.ki.dwExtraInfo = 0;
+ ip.ki.wVk = VK_MEDIA_PLAY_PAUSE; // virtual-key code for the "a" key
+ ip.ki.dwFlags = 0; // 0 for key press
+
+ SendInput(1, &ip, sizeof(INPUT));
+ // Release the "Play/Pause" key
+ ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release
+ SendInput(1, &ip, sizeof(INPUT));
+}
+
+int getVolume()
+{
+ IAudioEndpointVolume *g_pEndptVol = NULL;
+ HRESULT hr = S_OK;
+ IMMDeviceEnumerator *pEnumerator = NULL;
+ IMMDevice *pDevice = NULL;
+ OSVERSIONINFO VersionInfo;
+
+ ZeroMemory(&VersionInfo, sizeof(OSVERSIONINFO));
+ VersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+ GetVersionEx(&VersionInfo);
+ CoInitialize(NULL);
+
+ // Get enumerator for audio endpoint devices.
+ hr = CoCreateInstance(__uuidof(MMDeviceEnumerator),
+ NULL, CLSCTX_INPROC_SERVER,
+ __uuidof(IMMDeviceEnumerator),
+ (void**)&pEnumerator);
+
+ // Get default audio-rendering device.
+ hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &pDevice);
+
+ hr = pDevice->Activate(__uuidof(IAudioEndpointVolume),
+ CLSCTX_ALL, NULL, (void**)&g_pEndptVol);
+ float currentVal;
+ hr = g_pEndptVol->GetMasterVolumeLevelScalar(¤tVal);
+ fflush(stdout); // just in case
+
+ SAFE_RELEASE(pEnumerator)
+ SAFE_RELEASE(pDevice)
+ SAFE_RELEASE(g_pEndptVol)
+ CoUninitialize();
+ return ((int) round(100 * currentVal));
+
+}
+
+void setVolume(int vol)
+{
+ IAudioEndpointVolume *g_pEndptVol = NULL;
+ HRESULT hr = S_OK;
+ IMMDeviceEnumerator *pEnumerator = NULL;
+ IMMDevice *pDevice = NULL;
+ OSVERSIONINFO VersionInfo;
+
+ ZeroMemory(&VersionInfo, sizeof(OSVERSIONINFO));
+ VersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+ GetVersionEx(&VersionInfo);
+ CoInitialize(NULL);
+
+ // Get enumerator for audio endpoint devices.
+ hr = CoCreateInstance(__uuidof(MMDeviceEnumerator),
+ NULL, CLSCTX_INPROC_SERVER,
+ __uuidof(IMMDeviceEnumerator),
+ (void**)&pEnumerator);
+
+ // Get default audio-rendering device.
+ hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &pDevice);
+
+ hr = pDevice->Activate(__uuidof(IAudioEndpointVolume),
+ CLSCTX_ALL, NULL, (void**)&g_pEndptVol);
+ float got = (float)vol/100.0; // needs to be within 1.0 to 0.0
+ hr = g_pEndptVol->SetMasterVolumeLevelScalar(got, NULL);
+ fflush(stdout); // just in case
+
+ SAFE_RELEASE(pEnumerator)
+ SAFE_RELEASE(pDevice)
+ SAFE_RELEASE(g_pEndptVol)
+ CoUninitialize();
+}
+
+int main(int argc, char* argv[])
+{
+ OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
+
+ if (argc == 1)
+ {
+ isListOfObservers = false;
+ isSecure = false;
+ }
+ else if (argc == 2)
+ {
+ int value = atoi(argv[1]);
+ switch (value)
+ {
+ case 1:
+ isListOfObservers = true;
+ isSecure = false;
+ break;
+ case 2:
+ isListOfObservers = false;
+ isSecure = true;
+ break;
+ case 3:
+ isListOfObservers = true;
+ isSecure = true;
+ break;
+ case 4:
+ isSlowResponse = true;
+ break;
+ default:
+ PrintUsage();
+ break;
+ }
+ }
+ else
+ {
+ PrintUsage();
+ return -1;
+ }
+
+ // Create PlatformConfig object
+ PlatformConfig cfg {
+ OC::ServiceType::InProc,
+ OC::ModeType::Server,
+ "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+ 0, // Uses randomly available port
+ OC::QualityOfService::LowQos,
+ &ps
+ };
+
+ OCPlatform::Configure(cfg);
+ try
+ {
+ // Create the instance of the resource class
+ // (in this case instance of class 'MediaResource').
+ MediaResource myMedia;
+
+ // Invoke createResource function of class media.
+ myMedia.createResource();
+ cout << "Created resource." << std::endl;
+
+ // A condition variable will free the mutex it is given, then do a non-
+ // intensive block until 'notify' is called on it. In this case, since we
+ // don't ever call cv.notify, this should be a non-processor intensive version
+ // of while(true);
+ std::mutex blocker;
+ std::condition_variable cv;
+ std::unique_lock<std::mutex> lock(blocker);
+ cout <<"Waiting" << std::endl;
+ cv.wait(lock, []{return false;});
+ }
+ catch(OCException &e)
+ {
+ cout << "OCException in main : " << e.what() << endl;
+ }
+
+ // No explicit call to stop the platform.
+ // When OCPlatform::destructor is invoked, internally we do platform cleanup
+
+ return 0;
+}
+
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
},\r
{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/ad",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.ad"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } ,\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
"deviceuuid": "32323232-3232-3232-3232-323232323232",\r
"devowneruuid": "32323232-3232-3232-3232-323232323232",\r
"rowneruuid": "32323232-3232-3232-3232-323232323232",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
},\r
"cred": {\r
"creds": [\r
--- /dev/null
+{\r
+ "acl": {\r
+ "aclist": {\r
+ "aces": [\r
+ {\r
+ "subjectuuid": "*",\r
+ "resources": [\r
+ {\r
+ "href": "/oic/res",\r
+ "rel": "",\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
+ },\r
+ {\r
+ "href": "/oic/d",\r
+ "rel": "",\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
+ },\r
+ {\r
+ "href": "/oic/p",\r
+ "rel": "",\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
+ }\r
+ ],\r
+ "permission": 2\r
+ },\r
+ {\r
+ "subjectuuid": "*",\r
+ "resources": [\r
+ {\r
+ "href": "/oic/sec/doxm",\r
+ "rel": "",\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
+ {\r
+ "href": "/oic/sec/pstat",\r
+ "rel": "",\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
+ {\r
+ "href": "/oic/sec/acl",\r
+ "rel": "",\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
+ {\r
+ "href": "/oic/sec/cred",\r
+ "rel": "",\r
+ "rt": ["oic.r.cred"],\r
+ "if": ["oic.if.baseline"]\r
+ }\r
+ ],\r
+ "permission": 6\r
+ }\r
+ ]\r
+ },\r
+ "rowneruuid" : "64706169-7269-6e67-4465-765555494430"\r
+ },\r
+ "pstat": {\r
+ "isop": false,\r
+ "deviceuuid": "64706169-7269-6e67-4465-765555494430",\r
+ "rowneruuid": "64706169-7269-6e67-4465-765555494430",\r
+ "cm": 2,\r
+ "tm": 0,\r
+ "om": 3,\r
+ "sm": 3\r
+ },\r
+ "doxm": {\r
+ "oxms": [0],\r
+ "oxmsel": 0,\r
+ "sct": 1,\r
+ "owned": false,\r
+ "deviceuuid": "64706169-7269-6e67-4465-765555494430",\r
+ "devowneruuid": "",\r
+ "rowneruuid": "64706169-7269-6e67-4465-765555494430",\r
+ "x.com.samsung.dpc": false\r
+ }\r
+}\r
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
},\r
{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/ad",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.ad"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } ,\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/a/light",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.core"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 6\r
"deviceuuid": "31313131-3131-3131-3131-313131313131",\r
"devowneruuid": "32323232-3232-3232-3232-323232323232",\r
"rowneruuid": "31313131-3131-3131-3131-313131313131",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
},\r
"cred": {\r
"creds": [\r
#include <pthread.h>
#include <mutex>
#include <condition_variable>
-
+#include <getopt.h>
#include "OCPlatform.h"
#include "OCApi.h"
#include "OCPlatform.h"
#include "OCApi.h"
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+#include "platform_features.h"
+
using namespace OC;
using namespace std;
}
}
- void addInterface(const std::string& interface) const
+ void addInterface(const std::string& iface) const
{
- OCStackResult result = OC::OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
+ OCStackResult result = OC::OCPlatform::bindInterfaceToResource(m_resourceHandle, iface);
if (OC_STACK_OK != result)
{
cout << "Binding TypeName to Resource was unsuccessful\n";
// OCClient.cpp : Defines the entry point for the console application.
//
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_PTHREAD_H
+#include <pthread.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <Windows.h>
+#endif
#include <string>
#include <map>
#include <cstdlib>
-#include <pthread.h>
#include <mutex>
#include <condition_variable>
#include "OCPlatform.h"
{
try
{
- if(eCode == OC_STACK_OK && sequenceNumber != OC_OBSERVE_NO_OPTION)
+ if(eCode == OC_STACK_OK && sequenceNumber != -1)
{
if(sequenceNumber == OC_OBSERVE_REGISTER)
{
std::cout << "Observe registration action is successful" << std::endl;
}
- else if(sequenceNumber == OC_OBSERVE_DEREGISTER)
- {
- std::cout << "Observe De-registration action is successful" << std::endl;
- }
std::cout << "OBSERVE RESULT:"<<std::endl;
std::cout << "\tSequenceNumber: "<< sequenceNumber << std::endl;
}
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
{
OC::ModeType::Both,
"0.0.0.0",
0,
- OC::QualityOfService::LowQos,
+ OC::QualityOfService::HighQos,
&ps
};
#include "OCPlatform.h"
#include "OCApi.h"
+#if defined(HAVE_WINDOWS_H)
+#include <windows.h>
+#endif
+#include "platform_features.h"
+
using namespace OC;
struct dereference_compare
/// This sample provides steps to define an interface for a resource
/// (properties and methods) and host this resource on the server.
///
-
#include <functional>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
#include <mutex>
#include <condition_variable>
#include "OCPlatform.h"
#include "OCApi.h"
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+#include "platform_features.h"
using namespace OC;
using namespace std;
}
}
- void addInterface(const std::string& interface) const
+ void addInterface(const std::string& iface) const
{
- OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
+ OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, iface);
if (OC_STACK_OK != result)
{
cout << "Binding TypeName to Resource was unsuccessful\n";
m_interestedObservers.end());
}
+#if defined(_WIN32)
+ DWORD threadId = 0;
+ HANDLE threadHandle = INVALID_HANDLE_VALUE;
+#else
pthread_t threadId;
+#endif
cout << "\t\trequestFlag : Observer\n";
gObservation = 1;
// If we have not created the thread already, we will create one here.
if(!startedThread)
{
+#if defined(_WIN32)
+ threadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ChangeLightRepresentation, (void*)this, 0, &threadId);
+#else
pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this);
+#endif
startedThread = 1;
}
ehResult = OC_EH_OK;
#include "OCPlatform.h"
#include "OCApi.h"
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+#include "platform_features.h"
+
using namespace OC;
using namespace std;
namespace PH = std::placeholders;
}
}
- void addInterface(const std::string& interface) const
+ void addInterface(const std::string& iface) const
{
- OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
+ OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, iface);
if (OC_STACK_OK != result)
{
cout << "Binding TypeName to Resource was unsuccessful\n";
#include "OCPlatform.h"
#include "OCApi.h"
+
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+#include "platform_features.h"
+
using namespace OC;
static std::ostringstream requestURI;
--- /dev/null
+/* ****************************************************************\r
+ *\r
+ * Copyright 2016 Intel Corporation All Rights Reserved.\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#include <string>\r
+#include "winuiclient.h"\r
+#include <Windows.h>\r
+#include <Commctrl.h>\r
+#include <functional>\r
+\r
+extern int g_CurSliderVal;\r
+extern HWND hwndVolumeSlider, hwndVolumeExpectedLabel;\r
+using namespace WinUIClient;\r
+void LabelPrintf (HWND hwndEdit, TCHAR * szFormat, ...);\r
+\r
+WinUIClientApp::WinUIClientApp(OCPersistentStorage ps)\r
+ : persistentStorage(ps),\r
+ OBSERVE_TYPE_TO_USE(ObserveType::Observe)\r
+{\r
+\r
+}\r
+\r
+WinUIClientApp::~WinUIClientApp()\r
+{\r
+\r
+}\r
+\r
+void WinUIClientApp::Initialize()\r
+{\r
+ // Create PlatformConfig object\r
+ PlatformConfig cfg {\r
+ OC::ServiceType::InProc,\r
+ OC::ModeType::Both,\r
+ "0.0.0.0",\r
+ 0,\r
+ OC::QualityOfService::LowQos,\r
+ &persistentStorage\r
+ };\r
+\r
+ OCPlatform::Configure(cfg);\r
+}\r
+\r
+void WinUIClientApp::Run()\r
+{\r
+ try\r
+ {\r
+ // makes it so that all boolean values are printed as 'true/false' in this stream\r
+ std::cout.setf(std::ios::boolalpha);\r
+ // Find all resources\r
+ std::ostringstream requestURI;// << "?rt=core.media";\r
+ std::string s = OC_RSRVD_WELL_KNOWN_URI;\r
+ requestURI << s;\r
+\r
+ OCPlatform::findResource("", requestURI.str(),\r
+ CT_DEFAULT, std::bind(&WinUIClientApp::foundResource, this, std::placeholders::_1));\r
+ std::cout<< "Finding Resource... " <<std::endl;\r
+\r
+ // Find resource is done twice so that we discover the original resources a second time.\r
+ // These resources will have the same uniqueidentifier (yet be different objects), so that\r
+ // we can verify/show the duplicate-checking code in foundResource(above);\r
+ OCPlatform::findResource("", requestURI.str(),\r
+ CT_DEFAULT, std::bind(&WinUIClientApp::foundResource, this, std::placeholders::_1));\r
+ std::cout<< "Finding Resource for second time..." << std::endl;\r
+\r
+ }catch(OCException& e)\r
+ {\r
+ std::cerr << "Exception in main: "<<e.what();\r
+ }\r
+}\r
+\r
+void WinUIClientApp::FindResources()\r
+{\r
+ std::ostringstream requestURI;\r
+ requestURI << OC_RSRVD_WELL_KNOWN_URI;// << "?rt=core.media";\r
+ OCPlatform::findResource("", requestURI.str(),\r
+ CT_DEFAULT, std::bind(&WinUIClientApp::foundResource, this, std::placeholders::_1));\r
+}\r
+\r
+\r
+// Callback to found resources\r
+void WinUIClientApp::foundResource(std::shared_ptr<OCResource> resource)\r
+{\r
+ std::cout << "In foundResource\n";\r
+ std::string resourceURI;\r
+ std::string hostAddress;\r
+ try\r
+ {\r
+ {\r
+ std::lock_guard<std::mutex> lock(curResourceLock);\r
+ if (discoveredResources.find(resource->uniqueIdentifier()) == discoveredResources.end())\r
+ {\r
+ std::cout << "Found resource " << resource->uniqueIdentifier() <<\r
+ " for the first time on server with ID: "<< resource->sid()<<std::endl;\r
+ discoveredResources[resource->uniqueIdentifier()] = resource;\r
+ }\r
+ else\r
+ {\r
+ std::cout<<"Found resource "<< resource->uniqueIdentifier() << " again!"<<std::endl;\r
+ }\r
+\r
+ if (curResource)\r
+ {\r
+ std::cout << "Found another resource, ignoring"<<std::endl;\r
+ return;\r
+ }\r
+ }\r
+\r
+ // Do some operations with resource object.\r
+ if (resource)\r
+ {\r
+ std::cout<<"DISCOVERED Resource:"<<std::endl;\r
+ // Get the resource URI\r
+ resourceURI = resource->uri();\r
+ std::cout << "\tURI of the resource: " << resourceURI << std::endl;\r
+\r
+ // Get the resource host address\r
+ hostAddress = resource->host();\r
+ std::cout << "\tHost address of the resource: " << hostAddress << std::endl;\r
+\r
+ // Get the resource types\r
+ std::cout << "\tList of resource types: " << std::endl;\r
+ for(auto &resourceTypes : resource->getResourceTypes())\r
+ {\r
+ std::cout << "\t\t" << resourceTypes << std::endl;\r
+ }\r
+\r
+ // Get the resource interfaces\r
+ std::cout << "\tList of resource interfaces: " << std::endl;\r
+ for(auto &resourceInterfaces : resource->getResourceInterfaces())\r
+ {\r
+ std::cout << "\t\t" << resourceInterfaces << std::endl;\r
+ }\r
+\r
+ if (resourceURI == "/a/media")\r
+ {\r
+ curResource = resource;\r
+ // Call a local function which will internally invoke get API on the resource pointer\r
+ this->GetMediaRepresentation();\r
+ this->BeginObserving();\r
+ }\r
+ }\r
+ else\r
+ {\r
+ // Resource is invalid\r
+ std::cout << "Resource is invalid" << std::endl;\r
+ }\r
+\r
+ }\r
+ catch(std::exception& e)\r
+ {\r
+ std::cerr << "Exception in foundResource: "<< e.what() << std::endl;\r
+ }\r
+}\r
+\r
+// Local function to get representation of media resource\r
+void WinUIClientApp::GetMediaRepresentation()\r
+{\r
+ if (curResource)\r
+ {\r
+ std::cout << "Getting Media Representation..."<<std::endl;\r
+ // Invoke resource's get API with the callback parameter\r
+\r
+ QueryParamsMap test;\r
+ curResource->get(test, std::bind(&WinUIClientApp::onGet, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));\r
+\r
+ }\r
+ else\r
+ {\r
+ std::cout << "No Current Resource to GetMediaRepresentation..."<<std::endl;\r
+ }\r
+}\r
+\r
+// Callback handler on GET request\r
+void WinUIClientApp::onGet(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)\r
+{\r
+ try\r
+ {\r
+ if (eCode == OC_STACK_OK)\r
+ {\r
+ std::cout << "GET request was successful" << std::endl;\r
+ std::cout << "Resource URI: " << rep.getUri() << std::endl;\r
+\r
+ rep.getValue("state", mymedia.m_state);\r
+ rep.getValue("volume", mymedia.m_volume);\r
+ rep.getValue("name", mymedia.m_name);\r
+\r
+ std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+ std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+ std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+\r
+ g_CurSliderVal = mymedia.m_volume;\r
+ SendMessage(hwndVolumeSlider, TBM_SETPOS, TRUE, g_CurSliderVal);\r
+ LabelPrintf(hwndVolumeExpectedLabel,"Volume: %i", g_CurSliderVal);\r
+\r
+ }\r
+ else\r
+ {\r
+ std::cout << "onGET Response error: " << eCode << std::endl;\r
+ std::exit(-1);\r
+ }\r
+ }\r
+ catch(std::exception& e)\r
+ {\r
+ std::cout << "Exception: " << e.what() << " in onGet" << std::endl;\r
+ }\r
+}\r
+\r
+// Local function to put a different state for this resource\r
+void WinUIClientApp::PutMediaRepresentation()\r
+{\r
+ if (curResource)\r
+ {\r
+ OCRepresentation rep;\r
+\r
+ std::cout << "Putting media representation..."<<std::endl;\r
+\r
+ rep.setValue("state", mymedia.m_state);\r
+ rep.setValue("volume", mymedia.m_volume);\r
+\r
+ // Invoke resource's put API with rep, query map and the callback parameter\r
+ curResource->put(rep, QueryParamsMap(), std::bind(&WinUIClientApp::onPut, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));\r
+ }\r
+}\r
+\r
+// callback handler on PUT request\r
+void WinUIClientApp::onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)\r
+{\r
+ try\r
+ {\r
+ if (eCode == OC_STACK_OK)\r
+ {\r
+ std::cout << "PUT request was successful" << std::endl;\r
+\r
+ rep.getValue("state", mymedia.m_state);\r
+ rep.getValue("volume", mymedia.m_volume);\r
+ rep.getValue("name", mymedia.m_name);\r
+\r
+ std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+ std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+ std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+\r
+ }\r
+ else\r
+ {\r
+ std::cout << "onPut Response error: " << eCode << std::endl;\r
+ std::exit(-1);\r
+ }\r
+ }\r
+ catch(std::exception& e)\r
+ {\r
+ std::cout << "Exception: " << e.what() << " in onPut" << std::endl;\r
+ }\r
+}\r
+\r
+// Local function to put a different state for this resource\r
+void WinUIClientApp::PostMediaRepresentation()\r
+{\r
+ if (curResource)\r
+ {\r
+ OCRepresentation rep;\r
+\r
+ std::cout << "Posting media representation..."<<std::endl;\r
+\r
+ rep.setValue("state", mymedia.m_state);\r
+ rep.setValue("volume", mymedia.m_volume);\r
+\r
+ // Invoke resource's post API with rep, query map and the callback parameter\r
+ curResource->post(rep, QueryParamsMap(), std::bind(&WinUIClientApp::onPost, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));\r
+ }\r
+}\r
+\r
+void WinUIClientApp::onPost(const HeaderOptions& /*headerOptions*/,\r
+ const OCRepresentation& rep, const int eCode)\r
+{\r
+ try\r
+ {\r
+ if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED)\r
+ {\r
+ std::cout << "POST request was successful" << std::endl;\r
+\r
+ if (rep.hasAttribute("createduri"))\r
+ {\r
+ std::cout << "\tUri of the created resource: "\r
+ << rep.getValue<std::string>("createduri") << std::endl;\r
+ }\r
+ else\r
+ {\r
+ rep.getValue("state", mymedia.m_state);\r
+ rep.getValue("volume", mymedia.m_volume);\r
+ rep.getValue("name", mymedia.m_name);\r
+\r
+ std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+ std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+ std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+ }\r
+\r
+ }\r
+ else\r
+ {\r
+ std::cout << "onPost Response error: " << eCode << std::endl;\r
+ std::exit(-1);\r
+ }\r
+ }\r
+ catch (std::exception& e)\r
+ {\r
+ std::cout << "Exception: " << e.what() << " in onPost" << std::endl;\r
+ }\r
+}\r
+\r
+void WinUIClientApp::onPost2(const HeaderOptions& /*headerOptions*/,\r
+ const OCRepresentation& rep, const int eCode)\r
+{\r
+ try\r
+ {\r
+ if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED)\r
+ {\r
+ std::cout << "POST request was successful" << std::endl;\r
+\r
+ if (rep.hasAttribute("createduri"))\r
+ {\r
+ std::cout << "\tUri of the created resource: "\r
+ << rep.getValue<std::string>("createduri") << std::endl;\r
+ }\r
+ else\r
+ {\r
+ rep.getValue("state", mymedia.m_state);\r
+ rep.getValue("volume", mymedia.m_volume);\r
+ rep.getValue("name", mymedia.m_name);\r
+\r
+ std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+ std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+ std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+ }\r
+\r
+ }\r
+ else\r
+ {\r
+ std::cout << "onPost2 Response error: " << eCode << std::endl;\r
+ std::exit(-1);\r
+ }\r
+ }\r
+ catch(std::exception& e)\r
+ {\r
+ std::cout << "Exception: " << e.what() << " in onPost2" << std::endl;\r
+ }\r
+\r
+}\r
+\r
+void WinUIClientApp::onObserve(const HeaderOptions /*headerOptions*/, const OCRepresentation& rep,\r
+ const int& eCode, const int& sequenceNumber)\r
+{\r
+ try\r
+ {\r
+ if (eCode == OC_STACK_OK && sequenceNumber != OC_OBSERVE_NO_OPTION)\r
+ {\r
+ if (sequenceNumber == OC_OBSERVE_REGISTER)\r
+ {\r
+ std::cout << "Observe registration action is successful" << std::endl;\r
+ }\r
+ else if (sequenceNumber == OC_OBSERVE_DEREGISTER)\r
+ {\r
+ std::cout << "Observe De-registration action is successful" << std::endl;\r
+ }\r
+\r
+ std::cout << "OBSERVE RESULT:"<<std::endl;\r
+ std::cout << "\tSequenceNumber: "<< sequenceNumber << std::endl;\r
+ rep.getValue("state", mymedia.m_state);\r
+ rep.getValue("volume", mymedia.m_volume);\r
+ rep.getValue("name", mymedia.m_name);\r
+\r
+ std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+ std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+ std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+\r
+ g_CurSliderVal = mymedia.m_volume;\r
+ SendMessage(hwndVolumeSlider, TBM_SETPOS, TRUE, g_CurSliderVal);\r
+ LabelPrintf(hwndVolumeExpectedLabel,"Volume: %i", g_CurSliderVal);\r
+ }\r
+ else\r
+ {\r
+ if (sequenceNumber == OC_OBSERVE_NO_OPTION)\r
+ {\r
+ std::cout << "Observe registration or de-registration action is failed" << std::endl;\r
+ }\r
+ else\r
+ {\r
+ std::cout << "onObserve Response error: " << eCode << std::endl;\r
+ std::exit(-1);\r
+ }\r
+ }\r
+ }\r
+ catch (std::exception& e)\r
+ {\r
+ std::cout << "Exception: " << e.what() << " in onObserve" << std::endl;\r
+ }\r
+\r
+}\r
+\r
+void WinUIClientApp::BeginObserving()\r
+{\r
+ if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)\r
+ std::cout << std::endl << "Observe is used." << std::endl << std::endl;\r
+ else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)\r
+ std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl;\r
+\r
+ curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), std::bind(&WinUIClientApp::onObserve, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));\r
+}\r
+\r
+void WinUIClientApp::CancelObserving()\r
+{\r
+ std::cout<<"Cancelling Observe..."<<std::endl;\r
+ OCStackResult result = curResource->cancelObserve();\r
+}\r
+\r
+std::shared_ptr<OCResource> WinUIClientApp::GetResource()\r
+{\r
+ return curResource;\r
+}\r
+\r
+int WinUIClientApp::observe_count()\r
+{\r
+ static int oc = 0;\r
+ return ++oc;\r
+}\r
+\r
--- /dev/null
+/* ****************************************************************
+ *
+ * Copyright 2016 Intel Corporation All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef WINUICLIENT_H_
+#define WINUICLIENT_H_
+
+#include <memory>
+#include <mutex>
+#include <map>
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "OCResource.h"
+
+using namespace OC;
+namespace WinUIClient{
+
+ class Media
+ {
+ public:
+
+ bool m_state;
+ int m_volume;
+ std::string m_name;
+
+ Media() : m_state(false), m_volume(0), m_name("")
+ {
+ }
+ };
+
+ class WinUIClientApp
+ {
+ public:
+ WinUIClientApp(OCPersistentStorage ps);
+ ~WinUIClientApp();
+
+ void Initialize();
+ void Run();
+ void FindResources();
+ void GetMediaRepresentation();
+ void PutMediaRepresentation();
+ void PostMediaRepresentation();
+ void BeginObserving();
+ void CancelObserving();
+
+ std::shared_ptr<OCResource> GetResource();
+ Media GetMedia(){return mymedia;}
+ void SetMedia(bool state, int volume){mymedia.m_state = state; mymedia.m_volume=volume;}
+ bool observing;
+
+ private:
+ void foundResource(std::shared_ptr<OCResource> resource);
+ void onGet(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode);
+ void onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode);
+ void onPost(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode);
+ void onPost2(const HeaderOptions& /*headerOptions*/,const OCRepresentation& rep, const int eCode);
+ void onObserve(const HeaderOptions /*headerOptions*/, const OCRepresentation& rep, const int& eCode, const int& sequenceNumber);
+ private:
+ int observe_count();
+
+ private:
+ typedef std::map<OCResourceIdentifier, std::shared_ptr<OCResource>> DiscoveredResourceMap;
+
+ OCPersistentStorage persistentStorage;
+ Media mymedia;
+ DiscoveredResourceMap discoveredResources;
+ std::shared_ptr<OCResource> curResource;
+ ObserveType OBSERVE_TYPE_TO_USE;
+ std::mutex curResourceLock;
+ };
+
+}
+
+#endif
+
--- /dev/null
+/* ****************************************************************
+ *
+ * Copyright 2016 Intel Corporation All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <string>
+#include "winuiclient.h"
+
+#include <Windows.h>
+#include <Commctrl.h>
+
+#define ID_TRACKBAR 0x50505
+#define ID_BUTTONPLAYPAUSE 0xFFF0
+#define ID_BUTTONFIND 0xFFF1
+#define ID_BUTTONGET 0xFFF2
+#define ID_BUTTONPUT 0xFFF3
+#define ID_BUTTONPOST 0xFFF4
+#define ID_BUTTONBEGINOBSERVE 0xFFF5
+#define ID_BUTTONCANCELOBSERVE 0xFFF6
+
+int g_CurSliderVal = 0;
+
+HWND hwnd, icon_button, hwndVolumeSlider, hwndVolumeExpectedLabel;
+HWND hwndButtonPlayPause, hwndButtonFind, hwndButtonGet, hwndButtonPut, hwndButtonPost, hwndButtonBeginObserve, hwndButtonCancelObserve;
+HINSTANCE hInstance, g_hinstTrackBar, g_hinstVolumeSlider, g_hinstVolumeLabel;
+HANDLE Timer, Thread;
+HICON hIcon1;
+HBRUSH g_BkgndBrush;
+
+WinUIClient::WinUIClientApp* app = NULL;
+
+LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
+void LabelPrintf (HWND hwndEdit, TCHAR * szFormat, ...);
+HWND WINAPI CreateTrackbar(HWND parent, int x, int y, int w, int h,UINT iMin, UINT iMax, UINT iSelMin, UINT iSelMax);
+HWND WINAPI CreateLabel(HWND parent, LPCTSTR lpText, int x, int y, int w, int h);
+HWND WINAPI CreateButton(HWND parent, UINT_PTR id, LPCTSTR caption, int x, int y, int w, int h);
+
+FILE* client_open(const char* /*path*/, const char *mode)
+{
+ return fopen("./oic_svr_db_client.dat", mode);
+}
+
+int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
+ LPSTR lpCmdLine, int nCmdShow )
+{
+ MSG msg;
+ WNDCLASS wc = {sizeof(WNDCLASS)};
+ wc.lpszClassName = TEXT( "Static Control" );
+ wc.hInstance = hInstance ;
+ wc.hbrBackground = GetSysColorBrush(COLOR_MENU);
+ wc.lpfnWndProc = WndProc;
+ wc.hIcon = LoadIcon (NULL, IDI_APPLICATION);
+ wc.hCursor = LoadCursor (NULL, IDC_ARROW);
+
+ RegisterClass(&wc);
+ hwnd = CreateWindow( wc.lpszClassName, TEXT("IoTivity Media Client - Windows UI"),
+ WS_OVERLAPPEDWINDOW ^ WS_THICKFRAME,
+ 100, 100, 275, 170, 0, 0, hInstance, 0);
+
+ InitCommonControls(); // loads common control's DLL
+
+ hwndVolumeSlider =
+ CreateTrackbar(hwnd,
+ 10,10,
+ 170,40,
+ 0,100,
+ 0,0);
+ hwndVolumeExpectedLabel =
+ CreateLabel(hwnd,
+ "Expected Volume",
+ 10,50,
+ 240,30);
+
+ LabelPrintf(hwndVolumeExpectedLabel,
+ "Expected Volume: %i",
+ 0);
+
+ hwndButtonPlayPause =
+ CreateButton(hwnd,
+ ID_BUTTONPLAYPAUSE,
+ "PlayPause",
+ 180,10,
+ 80,35);
+
+ hwndButtonFind =
+ CreateButton(hwnd,
+ ID_BUTTONFIND,
+ "Find",
+ 10,75,
+ 64,25);
+
+ hwndButtonGet =
+ CreateButton(hwnd,
+ ID_BUTTONGET,
+ "Get",
+ 10,105,
+ 64,25);
+
+ hwndButtonPut =
+ CreateButton(hwnd,
+ ID_BUTTONPUT,
+ "Put",
+ 80,75,
+ 64,25);
+
+ hwndButtonPost =
+ CreateButton(hwnd,
+ ID_BUTTONPOST,
+ "Post",
+ 80,105,
+ 64,25);
+ hwndButtonBeginObserve =
+ CreateButton(hwnd,
+ ID_BUTTONBEGINOBSERVE,
+ "Bgn Obs",
+ 150,75,
+ 64,25);
+ hwndButtonCancelObserve =
+ CreateButton(hwnd,
+ ID_BUTTONCANCELOBSERVE,
+ "Cncl Obs",
+ 150,105,
+ 64,25);
+
+
+ ShowWindow(hwnd, nCmdShow);
+ UpdateWindow(hwnd);
+
+ while (GetMessage(&msg, NULL, 0, 0))
+ {
+ TranslateMessage(&msg);
+ DispatchMessage(&msg);
+ }
+
+ return (int) msg.wParam;
+}
+
+LRESULT
+CALLBACK
+WndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
+{
+ HDC hDC;
+ RECT rect;
+ WinUIClient::Media myMedia;
+
+ switch(msg){
+ case WM_HSCROLL:
+ switch (LOWORD(wParam)) {
+ case TB_ENDTRACK:
+ g_CurSliderVal = SendMessage(hwndVolumeSlider, TBM_GETPOS, 0, 0);
+ LabelPrintf(hwndVolumeExpectedLabel,"Volume: %i", g_CurSliderVal);
+
+ myMedia = app->GetMedia();
+ myMedia.m_volume = g_CurSliderVal;
+ app->SetMedia(myMedia.m_state, myMedia.m_volume);
+ app->PostMediaRepresentation();
+ break;
+ }
+ break;
+ case WM_CREATE:
+ {
+ hIcon1 = LoadIcon (NULL, IDI_WARNING);
+ SendMessage(icon_button,BM_SETIMAGE,IMAGE_ICON,(LPARAM)hIcon1);
+ GetClientRect(hwnd, &rect);
+ g_BkgndBrush = GetSysColorBrush(COLOR_MENU);
+
+ OCPersistentStorage ps = {client_open, fread, fwrite, fclose, unlink };
+ app = new WinUIClient::WinUIClientApp(ps);
+ app->Initialize();
+ app->Run();
+ }
+ break;
+ case WM_DESTROY:
+
+ delete app;
+
+ PostQuitMessage(0);
+ break;
+ case WM_ERASEBKGND:
+ GetClientRect(hwnd, &rect);
+ hDC = GetDC(hwnd);
+ SelectObject((HDC)wParam, g_BkgndBrush);
+ Rectangle((HDC)hDC, rect.left, rect.top, rect.right, rect.bottom);
+ ReleaseDC(hwnd, hDC);
+ break;
+ case WM_SIZE:
+ break;
+ case WM_RBUTTONDOWN:
+ case WM_LBUTTONDOWN:
+ break;
+ case WM_MOUSELEAVE:
+ case WM_RBUTTONUP:
+ case WM_LBUTTONUP:
+ break;
+ case WM_COMMAND:
+ if (HIWORD(wParam) == BN_CLICKED)
+ {
+
+ switch (LOWORD(wParam))
+ {
+ case ID_BUTTONPLAYPAUSE:
+ myMedia = app->GetMedia();
+
+ // HACK: We are using m_state in a stateless way.
+ // True means "toggle". The server does not have state
+ // knowledge about whether or not media is playing on the
+ // system. It's dumb and hits the "PlayPause" key on the
+ // keyboard.
+ //
+ myMedia.m_state = true;
+ app->SetMedia(myMedia.m_state, myMedia.m_volume);
+ myMedia.m_state = false;
+
+ app->PutMediaRepresentation();
+ break;
+ case ID_BUTTONFIND:
+ app->FindResources();
+ break;
+ case ID_BUTTONGET:
+ app->GetMediaRepresentation();
+ break;
+ case ID_BUTTONPUT:
+ myMedia = app->GetMedia();
+ myMedia.m_volume = g_CurSliderVal;
+ app->SetMedia(myMedia.m_state, myMedia.m_volume);
+ app->PutMediaRepresentation();
+ break;
+ case ID_BUTTONPOST:
+ myMedia = app->GetMedia();
+ myMedia.m_volume = g_CurSliderVal;
+ app->SetMedia(myMedia.m_state, myMedia.m_volume);
+ app->PostMediaRepresentation();
+ break;
+ case ID_BUTTONBEGINOBSERVE:
+ app->BeginObserving();
+ break;
+ case ID_BUTTONCANCELOBSERVE:
+ app->CancelObserving();
+ break;
+ }
+ }
+ break;
+ default:
+ return DefWindowProc(hwnd, msg, wParam, lParam);
+ }
+
+ return 0;
+}
+
+#define GWL_HINSTANCE -6
+HWND WINAPI CreateButton(HWND parent,
+ UINT_PTR id,
+ LPCTSTR caption ,
+ int x,
+ int y,
+ int w,
+ int h
+ )
+{
+ HWND hwndButton = CreateWindow(
+ "BUTTON", // Predefined class; Unicode assumed
+ caption, // Button text
+ WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles
+ x, // x position
+ y, // y position
+ w, // Button width
+ h, // Button height
+ parent, // Parent window
+ (HMENU)id, // No menu.
+ (HINSTANCE)GetWindowLongPtr(parent, GWL_HINSTANCE),
+ NULL); // Pointer not needed.
+
+ return hwndButton;
+}
+
+HWND WINAPI CreateLabel(
+ HWND parent, // handle of parent window
+ LPCTSTR lpText,
+ int x,
+ int y,
+ int w,
+ int h
+)
+{
+ HWND hwndPowerLabel = CreateWindow("static", "ST_U",
+ WS_CHILD | WS_VISIBLE | WS_TABSTOP,
+ x, y, w, h,
+ parent, (HMENU)(501),
+ (HINSTANCE)GetWindowLongPtr(parent, GWL_HINSTANCE),
+ NULL);
+ SetWindowText(hwndPowerLabel, lpText);
+ return hwndPowerLabel;
+}
+
+// CreateTrackbar - creates and initializes a trackbar.
+//
+// Global variable
+// g_hinstTrackBar - instance handle
+//
+HWND WINAPI CreateTrackbar(
+ HWND parent, // handle of dialog box (parent window)
+ int x,
+ int y,
+ int w,
+ int h,
+ UINT iMin, // minimum value in trackbar range
+ UINT iMax, // maximum value in trackbar range
+ UINT iSelMin, // minimum value in trackbar selection
+ UINT iSelMax) // maximum value in trackbar selection
+{
+ HWND hwndVolumeSlider = CreateWindowEx(
+ 0, // no extended styles
+ TRACKBAR_CLASS, // class name
+ "Trackbar Control", // title (caption)
+ WS_CHILD |
+ WS_VISIBLE |
+ TBS_AUTOTICKS |
+ TBS_ENABLESELRANGE, // style
+ x,y,w,h, // position ,size
+ parent, // parent window
+ (HMENU)ID_TRACKBAR, // control identifier
+ (HINSTANCE)GetWindowLongPtr(parent, GWL_HINSTANCE),// instance
+ NULL // no WM_CREATE parameter
+ );
+
+ SendMessage(hwndVolumeSlider, TBM_SETRANGE,
+ (WPARAM) TRUE, // redraw flag
+ (LPARAM) MAKELONG(iMin, iMax)); // min. & max. positions
+
+ SendMessage(hwndVolumeSlider, TBM_SETPAGESIZE,
+ 0, (LPARAM) 4); // new page size
+
+ SendMessage(hwndVolumeSlider, TBM_SETSEL,
+ (WPARAM) FALSE, // redraw flag
+ (LPARAM) MAKELONG(iSelMin, iSelMax));
+
+ SendMessage(hwndVolumeSlider, TBM_SETPOS,
+ (WPARAM) TRUE, // redraw flag
+ (LPARAM) iSelMin);
+
+ SetFocus(hwndVolumeSlider);
+
+ return hwndVolumeSlider;
+}
+
+void LabelPrintf (HWND hwndEdit, TCHAR * szFormat, ...)
+{
+ TCHAR szBuffer [1024] ;
+ va_list pArgList ;
+
+ va_start (pArgList, szFormat) ;
+ wvsprintf (szBuffer, szFormat, pArgList) ;
+ va_end (pArgList) ;
+
+ SetWindowText(hwndEdit, szBuffer);
+}
+
template<>
struct AttributeTypeConvert<NullType>
{
- constexpr static AttributeType type = AttributeType::Null;
+ BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Null;
};
template<>
struct AttributeTypeConvert<int>
{
- constexpr static AttributeType type = AttributeType::Integer;
+ BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Integer;
};
template<>
struct AttributeTypeConvert<double>
{
- constexpr static AttributeType type = AttributeType::Double;
+ BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Double;
};
template<>
struct AttributeTypeConvert<bool>
{
- constexpr static AttributeType type = AttributeType::Boolean;
+ BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Boolean;
};
template<>
struct AttributeTypeConvert<std::string>
{
- constexpr static AttributeType type = AttributeType::String;
+ BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::String;
};
template<>
struct AttributeTypeConvert<OCRepresentation>
{
- constexpr static AttributeType type = AttributeType::OCRepresentation;
+ BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::OCRepresentation;
};
template<>
struct AttributeTypeConvert<std::vector<uint8_t>>
{
- constexpr static AttributeType type = AttributeType::Binary;
+ BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Binary;
};
std::ostream& operator << (std::ostream& os, const AttributeType at);
*/
OCStackResult setNetworkMonitorHandler(AdapterChangedCallback adapterHandler,
ConnectionChangedCallback connectionHandler);
+
+ /**
+ * Set port number to use.
+ * @param adapter transport adapter type to assign the specified port number.
+ * @param flag transport flag information.
+ * @param port the specified port number to use.
+ * @return Returns ::OC_STACK_OK if success.
+ */
+ OCStackResult setPortNumberToAssign(OCTransportAdapter adapter,
+ OCTransportFlags flag, uint16_t port);
+
+ /**
+ * Get the assigned port number.
+ * @param adapter transport adapter type to get the opened port number.
+ * @param flag transport flag information.
+ * @return Returns currently assigned port number.
+ */
+ uint16_t getAssignedPortNumber(OCTransportAdapter adapter, OCTransportFlags flag);
}
}
#include <memory>
#include <string>
-
#include <OCApi.h>
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(){}
};
}
ObserveCallback callback;
ObserveContext(ObserveCallback cb) : callback(cb){}
};
+
+ struct DirectPairingContext
+ {
+ DirectPairingCallback callback;
+ DirectPairingContext(DirectPairingCallback cb) : callback(cb){}
+
+ };
}
class InProcClientWrapper : public IClientWrapper
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;
#include <map>
#include <memory>
#include <iterator>
+#if defined(_MSC_VER)
+#include <functional>
+#endif
#include "octypes.h"
#include "OCHeaderOption.h"
class OCResource;
class OCResourceRequest;
class OCResourceResponse;
+ class OCDirectPairing;
} // namespace OC
namespace OC
{
+#if defined(_MSC_VER)
+ extern std::ostream& oclog();
+#else
typedef boost::iostreams::stream<OC::oc_log_stream> log_target_t;
namespace detail
{
return detail::oclog_target();
};
-
+#endif
} // namespace OC
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;
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
--- /dev/null
+//******************************************************************
+//
+// 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_
OCHeaderOption(const OCHeaderOption&) = default;
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCHeaderOption(OCHeaderOption&& o)
+ {
+ std::memmove(this, &o, sizeof(o));
+ }
+#else
OCHeaderOption(OCHeaderOption&&) = default;
+#endif
OCHeaderOption& operator=(const OCHeaderOption&) = default;
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCHeaderOption& operator=(OCHeaderOption&& o)
+ {
+ std::memmove(this, &o, sizeof(o));
+ }
+#else
OCHeaderOption& operator=(OCHeaderOption&&) = default;
+#endif
/**
* API to get Option ID
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,
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);
}
}
#include "OCResourceRequest.h"
#include "OCResourceResponse.h"
#include "OCRepresentation.h"
+#include "OCDirectPairing.h"
#include "oc_logger.hpp"
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;
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.
#ifndef OC_REPRESENTATION_H_
#define OC_REPRESENTATION_H_
-
#include <string>
#include <sstream>
#include <vector>
// this fix will work in the meantime.
OCRepresentation(): m_interfaceType(InterfaceType::None){}
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCRepresentation(OCRepresentation&& o)
+ {
+ std::memmove(this, &o, sizeof(o));
+ }
+#else
OCRepresentation(OCRepresentation&&) = default;
+#endif
OCRepresentation(const OCRepresentation&) = default;
OCRepresentation& operator=(const OCRepresentation&) = default;
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCRepresentation& operator=(OCRepresentation&& o)
+ {
+ std::memmove(this, &o, sizeof(o));
+ return *this;
+ }
+#else
OCRepresentation& operator=(OCRepresentation&&) = default;
+#endif
virtual ~OCRepresentation(){}
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);
void addResourceInterface(const std::string& str);
+ void addDataModelVersion(const std::string& str);
+
bool emptyData() const;
int numberOfAttributes() const;
m_values[str] = std::forward<T>(val);
}
+ const std::map<std::string, AttributeValue>& getValues() const {
+ return m_values;
+ }
+
/**
* Retrieve the attribute value associated with the supplied name
*
// Enable-if required to prevent conversions to alternate types. This prevents
// ambigious conversions in the case where conversions can include a number of
// types, such as the string constructor.
+#if (defined(_MSC_VER) ) || (defined(__GNUC__) && (__GNUC__ <= 5))
+ template<typename T, typename std::enable_if<
+ std::is_same<T, int>::value ||
+ std::is_same<T, double>::value ||
+ std::is_same<T, bool>::value ||
+ std::is_same<T, std::string>::value ||
+ std::is_same<T, OCRepresentation>::value ||
+ std::is_same<T, std::vector<int>>::value ||
+ std::is_same<T, std::vector<std::vector<int>>>::value ||
+ std::is_same<T, std::vector<std::vector<std::vector<int>>>>::value ||
+ std::is_same<T, std::vector<double>>::value ||
+ std::is_same<T, std::vector<std::vector<double>>>::value ||
+ std::is_same<T, std::vector<std::vector<std::vector<double>>>>::value ||
+ std::is_same<T, std::vector<bool>>::value ||
+ std::is_same<T, std::vector<std::vector<bool>>>::value ||
+ std::is_same<T, std::vector<std::vector<std::vector<bool>>>>::value ||
+ std::is_same<T, std::vector<std::string>>::value ||
+ std::is_same<T, std::vector<std::vector<std::string>>>::value ||
+ std::is_same<T, std::vector<std::vector<std::vector<std::string>>>>::value ||
+ std::is_same<T, std::vector<OCRepresentation>>::value ||
+ std::is_same<T, std::vector<std::vector<OCRepresentation>>>::value ||
+ std::is_same<T, std::vector<std::vector<std::vector<OCRepresentation>>>>::value
+ , int>::type = 0// enable_if
+ >
+#else
template<typename T, typename std::enable_if<
is_component<T,
remove_first<AttributeValue>::type
>::value
, int>::type = 0
>
+#endif
operator T() const
{
return this->getValue<T>();
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;
};
OCResourceIdentifier(const OCResourceIdentifier&) = default;
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCResourceIdentifier(OCResourceIdentifier&& o):
+ m_resourceUri(std::move(o.m_resourceUri)),
+ m_representation(o.m_representation)
+ {
+ }
+#else
OCResourceIdentifier(OCResourceIdentifier&&) = default;
+#endif
OCResourceIdentifier& operator=(const OCResourceIdentifier&) = delete;
public:
typedef std::shared_ptr<OCResource> Ptr;
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCResource(OCResource&& o):
+ m_clientWrapper(std::move(o.m_clientWrapper)),
+ m_uri(std::move(o.m_uri)),
+ m_resourceId(std::move(o.m_resourceId)),
+ m_devAddr(std::move(o.m_devAddr)),
+ m_useHostString(o.m_useHostString),
+ m_isObservable(o.m_isObservable),
+ m_isCollection(o.m_isCollection),
+ m_resourceTypes(std::move(o.m_resourceTypes)),
+ m_interfaces(std::move(o.m_interfaces)),
+ m_children(std::move(m_children)),
+ m_observeHandle(std::move(m_observeHandle)),
+ m_headerOptions(std::move(m_headerOptions))
+ {
+ }
+#else
OCResource(OCResource&&) = default;
- OCResource& operator=(OCResource&&) = default;
+#endif
+ // Explicitly delete the copy ctor since VS2013 would try to generate one, and
+ // the standard says that defaulting the move ctor should delete the copy ctor.
+ OCResource(const OCResource&) = delete;
+
+ // We cannot support copy/move assigns since OCResourceIdentifier doesn't.
+ OCResource& operator=(OCResource&&) = delete;
+ OCResource& operator=(const OCResource&) = delete;
/**
* Virtual destructor
m_resourceUri{},
m_queryParameters{},
m_requestHandlerFlag{},
+ m_messageID{},
m_representation{},
m_observationInfo{},
m_headerOptions{},
{
}
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCResourceRequest(OCResourceRequest&& o):
+ m_requestType(std::move(o.m_requestType)),
+ m_resourceUri(std::move(o.m_resourceUri)),
+ m_queryParameters(std::move(o.m_queryParameters)),
+ m_requestHandlerFlag(o.m_requestHandlerFlag),
+ m_representation(std::move(o.m_representation)),
+ m_observationInfo(std::move(o.m_observationInfo)),
+ m_headerOptions(std::move(o.m_headerOptions)),
+ m_requestHandle(std::move(o.m_requestHandle)),
+ m_resourceHandle(std::move(o.m_resourceHandle))
+ {
+ }
+ OCResourceRequest& operator=(OCResourceRequest&& o)
+ {
+ m_requestType = std::move(o.m_requestType);
+ m_resourceUri = std::move(o.m_resourceUri);
+ m_queryParameters = std::move(o.m_queryParameters);
+ m_requestHandlerFlag = o.m_requestHandlerFlag;
+ m_representation = std::move(o.m_representation);
+ m_observationInfo = std::move(o.m_observationInfo);
+ m_headerOptions = std::move(o.m_headerOptions);
+ m_requestHandle = std::move(o.m_requestHandle);
+ m_resourceHandle = std::move(o.m_resourceHandle);
+ }
+#else
OCResourceRequest(OCResourceRequest&&) = default;
OCResourceRequest& operator=(OCResourceRequest&&) = default;
+#endif
+
/**
* Virtual destructor
*/
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;
m_requestHandlerFlag = requestHandlerFlag;
}
+ void setMessageID(int16_t messageID)
+ {
+ m_messageID = messageID;
+ }
+
void setObservationInfo(const ObservationInfo& observationInfo)
{
m_observationInfo = observationInfo;
{
}
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCResourceResponse(OCResourceResponse&& o):
+ m_newResourceUri(std::move(o.m_newResourceUri)),
+ m_errorCode(o.m_errorCode),
+ m_headerOptions(std::move(o.m_headerOptions)),
+ m_interface(std::move(o.m_interface)),
+ m_representation(std::move(o.m_representation)),
+ m_requestHandle(std::move(o.m_requestHandle)),
+ m_resourceHandle(std::move(o.m_resourceHandle)),
+ m_responseResult(std::move(o.m_responseResult))
+ {
+ }
+ OCResourceResponse& operator=(OCResourceResponse&& o)
+ {
+ m_newResourceUri = std::move(o.m_newResourceUri);
+ m_errorCode = o.m_errorCode;
+ m_headerOptions = std::move(o.m_headerOptions);
+ m_interface = std::move(o.m_interface);
+ m_representation = std::move(o.m_representation);
+ m_requestHandle = std::move(o.m_requestHandle);
+ m_resourceHandle = std::move(o.m_resourceHandle);
+ m_responseResult = std::move(o.m_responseResult);
+ }
+#else
OCResourceResponse(OCResourceResponse&&) = default;
OCResourceResponse& operator=(OCResourceResponse&&) = default;
+#endif
virtual ~OCResourceResponse(void) {}
/**
* @param rep reference to the resource's representation
* @param interface specifies the interface
*/
- void setResourceRepresentation(OCRepresentation& rep, std::string interface) {
- m_interface = interface;
+ void setResourceRepresentation(OCRepresentation& rep, std::string iface) {
+ m_interface = iface;
m_representation = rep;
}
* @param rep rvalue reference to the resource's representation
* @param interface specifies the interface
*/
- void setResourceRepresentation(OCRepresentation&& rep, std::string interface) {
- setResourceRepresentation(rep, interface);
+ void setResourceRepresentation(OCRepresentation&& rep, std::string iface) {
+ setResourceRepresentation(rep, iface);
}
/**
template<typename T, typename = void>
struct is_vector
{
- constexpr static bool value = false;
+ BOOST_STATIC_CONSTEXPR bool value = false;
};
template<typename T>
>::type
>
{
- constexpr static bool value = true;
+ BOOST_STATIC_CONSTEXPR bool value = true;
};
// type trait to remove the first type from a parameter-packed list
template<typename ToTest, template <typename...> class Base, typename T>
struct is_component<ToTest, Base<T> >
{
- static constexpr bool value = std::is_same<ToTest, T>::value;
+ BOOST_STATIC_CONSTEXPR bool value = std::is_same<ToTest, T>::value;
};
// Recursive specialization to handle cases with multiple values
template<typename ToTest, template <typename...> class Base, typename T, typename ...Rest>
struct is_component<ToTest, Base<T, Rest...> >
{
- static constexpr bool value = std::is_same<ToTest, T>::value
+ BOOST_STATIC_CONSTEXPR bool value = std::is_same<ToTest, T>::value
|| is_component<ToTest, Base<Rest...> >::value;
};
} // namespace OC
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;}
};
}
return m_missingInterface;
}
- virtual const char* what() const noexcept
+ virtual const char* what() const BOOST_NOEXCEPT
{
std::string ret;
namespace OC
{
+
+#if defined(_WIN32)
+/** @todo: Remove temporary hacks to solve error C2059: syntax error: 'constant'*/
+#ifdef NO_ERROR
+#undef NO_ERROR
+#endif
+#ifdef DELETE
+#undef DELETE
+#endif
+#endif
+
namespace InitException
{
static const char NO_ERROR[] = "No Error";
static const char INVALID_ATTRIBUTE[] = "Invalid Attribute: ";
static const char INVALID_DEVICE_INFO[] = "Invalid Device Information";
static const char UNAUTHORIZED_REQUEST[] = "Unauthorized Request";
+ static const char TOO_LARGE_REQ[] = "Request Too Large";
static const char PDM_DB_NOT_INITIALIZED[] = "Provisioning DB is not initialized";
static const char DUPLICATE_UUID[] = "Duplicate UUID in DB";
static const char INCONSISTENT_DB[] = "Data in provisioning DB is inconsistent";
liboc_logger_env.AppendUnique(LIBS = ['gnustl_shared', 'log'])
liboc_logger_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,liboc_logger.so'])
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows']:
liboc_logger_env.AppendUnique(CFLAGS = ['-Wall', '-std=c99', '-fPIC'])
liboc_logger_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x', '-fPIC'])
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows', 'msys_nt']:
liboc_logger_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
######################################################################
# Source files and Targets
######################################################################
-liboc_logger_core = liboc_logger_env.SharedLibrary('oc_logger_core', 'c/oc_logger.c', OBJPREFIX='core_')
-liboc_logger = liboc_logger_env.SharedLibrary('oc_logger',
+
+oc_logger_libs = []
+
+if target_os in ['windows', 'msys_nt']:
+ # TODO: Add OC_EXPORT API prefixes to enable oc_logger DLL generation.
+ oc_logger_libs += liboc_logger_env.StaticLibrary('oc_logger',
['c/oc_logger.c', 'c/oc_console_logger.c', 'cpp/oc_ostream_logger.cpp'])
+else:
+ oc_logger_libs += Flatten(liboc_logger_env.SharedLibrary('oc_logger_core',
+ ['c/oc_logger.c'], OBJPREFIX='core_'))
+ oc_logger_libs += Flatten(liboc_logger_env.SharedLibrary('oc_logger',
+ ['c/oc_logger.c', 'c/oc_console_logger.c', 'cpp/oc_ostream_logger.cpp']))
-liboc_logger_env.InstallTarget([liboc_logger_core, liboc_logger], 'liboc_logger')
-liboc_logger_env.UserInstallTargetLib([liboc_logger_core, liboc_logger], 'liboc_logger')
+liboc_logger_env.InstallTarget(oc_logger_libs, 'oc_logger')
+liboc_logger_env.UserInstallTargetLib(oc_logger_libs, 'oc_logger')
liboc_logger_env.UserInstallTargetHeader('include/oc_logger.hpp', 'resource', 'oc_logger.hpp')
liboc_logger_env.UserInstallTargetHeader('include/oc_logger.h', 'resource', 'oc_logger.h')
liboc_logger_env.UserInstallTargetHeader('include/oc_logger_types.h', 'resource', 'oc_logger_types.h')
######################################################################
examples_env.PrependUnique(CPPPATH = ['../include'])
examples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-examples_env.AppendUnique(LIBS = ['oc_logger', 'stdc++'])
+examples_env.AppendUnique(LIBS = ['oc_logger'])
+examples_env.Append(LIBS = ['c_common'])
+
+compiler = env.get('CC')
+if compiler != 'cl':
+ examples_env.AppendUnique(LIBS = ['stdc++'])
target_os = env.get('TARGET_OS')
if target_os == 'android':
examples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
examples_env.AppendUnique(LIBS = ['gnustl_shared'])
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows']:
examples_env.AppendUnique(CFLAGS = Split('-Wall -std=c99 -Werror'))
examples_env.AppendUnique(CXXFLAGS = Split('-Wall -std=c++0x'))
{}
public:
- inline void flush() noexcept { return oc_log_flush(m_log.get()); }
- inline void set_level(const oc_log_level new_level) noexcept { return oc_log_set_level(m_log.get(), new_level); }
- inline int set_module(const std::string& module_name) noexcept { return oc_log_set_module(m_log.get(), module_name.c_str()); }
+ inline void flush() BOOST_NOEXCEPT { return oc_log_flush(m_log.get()); }
+ inline void set_level(const oc_log_level new_level) BOOST_NOEXCEPT { return oc_log_set_level(m_log.get(), new_level); }
+ inline int set_module(const std::string& module_name) BOOST_NOEXCEPT { return oc_log_set_module(m_log.get(), module_name.c_str()); }
public:
std::streamsize write(const char_type *s, std::streamsize n)
])
target_os = env.get('TARGET_OS')
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
ocprovision_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-fPIC'])
if target_os == 'android':
'../../oc_logger/include',
'../../csdk/connectivity/api',
'../../csdk/security/include',
+ '../../csdk/security/include/internal',
'../../csdk/security/provisioning/include',
'../../csdk/security/provisioning/include/oxm',
'../../csdk/security/provisioning/include/internal'
])
target_os = env.get('TARGET_OS')
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
examples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
# Note: 'pthread' is in libc for android. On other platform, if use
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
},\r
{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/ad",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.ad"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/amacl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.amacl"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } \r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
+ }\r
],\r
"permission": 2\r
}\r
]\r
},\r
"rowneruuid" : "61646D69-6E44-6576-6963-655575696430"\r
- }, \r
+ },\r
"pstat": {\r
"isop": true,\r
"cm": 0,\r
"sct": 1,\r
"owned": true,\r
"deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
- "dpc": false,\r
+ "x.com.samsung.dpc": false,\r
"devowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
"rowneruuid": "61646D69-6E44-6576-6963-655575696430"\r
}\r
#include "OCProvisioningManager.h"
#include "oxmjustworks.h"
#include "oxmrandompin.h"
+#include "aclresource.h"
+#include "utlist.h"
#define MAX_URI_LENGTH (64)
#define MAX_PERMISSION_LENGTH (5)
+#define ACL_RESRC_ARRAY_SIZE (3)
#define CREATE (1)
#define READ (2)
#define UPDATE (4)
#define DISCOVERY_TIMEOUT 5
+static const OicSecPrm_t SUPPORTED_PRMS[1] =
+{
+ PRM_PRE_CONFIGURED,
+};
+
using namespace OC;
DeviceList_t pUnownedDevList, pOwnedDevList;
static int transferDevIdx, ask = 1;
+static OicSecPconf_t g_pconf;
static FILE* client_open(const char *UNUSED_PARAM, const char *mode)
{
std::cout << " 7. Unlink Devices"<<std::endl;
std::cout << " 8. Remove Device"<<std::endl;
std::cout << " 9. Get Linked Devices"<<std::endl;
- std::cout << " 10. Get Device Status"<<std::endl;
- std::cout << " 11. Exit loop"<<std::endl;
+ std::cout << " 10. Get Device Status"<<std::endl;
+ std::cout << " 11. Provision Direct-Pairing Configuration"<<std::endl;
+ std::cout << " 12. Exit loop"<<std::endl;
}
void moveTransferredDevice()
*/
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));
- }
}
/**
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)
return -1;
}
- acl->resources[i] = OICStrdup(temp_rsc);
+ rsrc->href = OICStrdup(temp_rsc);
OICFree(temp_rsc);
- if (NULL == acl->resources[i])
+
+ char* rsrc_in = NULL;
+ int arrLen = 0;
+ while(1)
{
- OIC_LOG(ERROR, TAG, "Error while memory allocation");
- return -1;
+ printf(" Enter Number of resource type for [%s]: ", rsrc_in);
+ for(int ret=0; 1!=ret; )
+ {
+ ret = scanf("%d", &arrLen);
+ for( ; 0x20<=getchar(); ); // for removing overflow garbages
+ // '0x20<=code' is character region
+ }
+ if(0 < arrLen && ACL_RESRC_ARRAY_SIZE >= arrLen)
+ {
+ break;
+ }
+ printf(" Entered Wrong Number. Please Enter under %d Again\n", ACL_RESRC_ARRAY_SIZE);
+ }
+
+ rsrc->typeLen = arrLen;
+ rsrc->types = (char**)OICCalloc(arrLen, sizeof(char*));
+ if(!rsrc->types)
+ {
+ OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+ goto error;
+ }
+
+ for(int i = 0; i < arrLen; i++)
+ {
+ printf(" Enter ResourceType[%d] Name: ", i+1);
+ for(int ret=0; 1!=ret; )
+ {
+ ret = scanf("%64ms", &rsrc_in); // '128' is ACL_RESRC_MAX_LEN
+ for( ; 0x20<=getchar(); ); // for removing overflow garbages
+ // '0x20<=code' is character region
+ }
+ rsrc->types[i] = OICStrdup(rsrc_in);
+ OICFree(rsrc_in);
+ if(!rsrc->types[i])
+ {
+ OIC_LOG(ERROR, TAG, "createAcl: OICStrdup error return");
+ goto error;
+ }
+ }
+
+ while(1)
+ {
+ printf(" Enter Number of interface name for [%s]: ", rsrc_in);
+ for(int ret=0; 1!=ret; )
+ {
+ ret = scanf("%d", &arrLen);
+ for( ; 0x20<=getchar(); ); // for removing overflow garbages
+ // '0x20<=code' is character region
+ }
+ if(0 < arrLen && ACL_RESRC_ARRAY_SIZE >= arrLen)
+ {
+ break;
+ }
+ printf(" Entered Wrong Number. Please Enter under %d Again\n", ACL_RESRC_ARRAY_SIZE);
+ }
+
+ rsrc->interfaceLen = arrLen;
+ rsrc->interfaces = (char**)OICCalloc(arrLen, sizeof(char*));
+ if(!rsrc->interfaces)
+ {
+ OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
+ goto error;
+ }
+
+ for(int i = 0; i < arrLen; i++)
+ {
+ printf(" Enter ResourceType[%d] Name: ", i+1);
+ for(int ret=0; 1!=ret; )
+ {
+ ret = scanf("%64ms", &rsrc_in); // '128' is ACL_RESRC_MAX_LEN
+ for( ; 0x20<=getchar(); ); // for removing overflow garbages
+ // '0x20<=code' is character region
+ }
+ rsrc->interfaces[i] = OICStrdup(rsrc_in);
+ OICFree(rsrc_in);
+ if(!rsrc->interfaces[i])
+ {
+ OIC_LOG(ERROR, TAG, "createAcl: OICStrdup error return");
+ goto error;
+ }
}
+
}
+
// Set Permission
do
{
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 );
if (1 != ret)
{
printf("Error while input\n");
- return -1;
+ goto error;
}
for (int k = 0, j = 0; temp_id[k] != '\0'; k++)
OICFree(temp_id);
return 0;
+
+error:
+ DeleteACLList(acl);
+ return -1;
}
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 };
}
case 11:
+ {
+ unsigned int devNum;
+
+ if (!pOwnedDevList.size())
+ {
+ std::cout <<"There are no Owned devices yet,"
+ " may need to discover"<<std::endl;
+ break;
+ }
+
+ for (unsigned int i = 0; i < pOwnedDevList.size(); i++ )
+ {
+ std::cout << i+1 << ": "<< pOwnedDevList[i]->getDeviceID() <<" From IP:";
+ std::cout << pOwnedDevList[i]->getDevAddr() <<std::endl;
+ }
+
+ std::cout <<"Select device number: "<<std::endl;
+ std::cin >> devNum;
+ if (devNum > pOwnedDevList.size())
+ {
+ std::cout <<"Invalid device number"<<std::endl;
+ break;
+ }
+
+ ask = 0;
+ provisionDP(devNum);
+
+ break;
+ }
+ case 12:
default:
out = 1;
break;
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());
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);
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);
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;
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);
}
auto csdkLock = OCPlatform_impl::Instance().csdkLock();
auto cLock = csdkLock.lock();
- if(cLock)
+ if (cLock)
{
std::lock_guard<std::recursive_mutex> lock(*cLock);
OCStackResult OCSecure::setDisplayPinCB(GeneratePinCallback displayPin)
{
- if(!displayPin)
+ if (!displayPin)
{
oclog() <<"displayPin can't be null";
return OC_STACK_INVALID_PARAM;
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);
OCSecureResource::~OCSecureResource()
{
- if(devPtr)
+ if (devPtr)
{
OCDeleteDiscoveredDevices(devPtr);
}
OCStackResult OCSecureResource::doOwnershipTransfer(ResultCallBack resultCallback)
{
- if(!resultCallback)
+ if (!resultCallback)
{
oclog() <<"Result callback can't be null";
return OC_STACK_INVALID_CALLBACK;
OCStackResult result;
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
ProvisionContext* context = new ProvisionContext(resultCallback);
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;
OCStackResult result;
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
ProvisionContext* context = new ProvisionContext(resultCallback);
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;
OCStackResult result;
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
ProvisionContext* context = new ProvisionContext(resultCallback);
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;
OCStackResult result;
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
ProvisionContext* context = new ProvisionContext(resultCallback);
OCStackResult OCSecureResource::unlinkDevices(const OCSecureResource &device2,
ResultCallBack resultCallback)
{
- if(!resultCallback)
+ if (!resultCallback)
{
oclog() << "Result calback can't be null";
return OC_STACK_INVALID_CALLBACK;
OCStackResult result;
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
ProvisionContext* context = new ProvisionContext(resultCallback);
OCStackResult OCSecureResource::removeDevice(unsigned short waitTimeForOwnedDeviceDiscovery,
ResultCallBack resultCallback)
{
- if(!resultCallback)
+ if (!resultCallback)
{
oclog() << "Result calback can't be null";
return OC_STACK_INVALID_CALLBACK;
OCStackResult result;
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
ProvisionContext* context = new ProvisionContext(resultCallback);
auto devUuid = devPtr->doxm->deviceID;
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
std::lock_guard<std::recursive_mutex> lock(*cLock);
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("");
if (OC_STACK_OK == ConvertUuidToStr(&(devPtr->doxm->deviceID), &devID))
{
deviceId << devID;
+ free(devID);
}
else
{
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));
+ }
}
namespace
{
- CAManager::AdapterChangedCallback g_adapterHandler = NULL;
- CAManager::ConnectionChangedCallback g_connectionHandler = NULL;
+ CAManager::AdapterChangedCallback g_adapterHandler = nullptr;
+ CAManager::ConnectionChangedCallback g_connectionHandler = nullptr;
+}
+
+OCStackResult convertCAResultToOCResult(CAResult_t caResult)
+{
+ switch (caResult)
+ {
+ case CA_STATUS_OK:
+ return OC_STACK_OK;
+ case CA_STATUS_INVALID_PARAM:
+ return OC_STACK_INVALID_PARAM;
+ case CA_STATUS_FAILED:
+ return OC_STACK_ERROR;
+ case CA_NOT_SUPPORTED:
+ return OC_STACK_NOTIMPL;
+ default:
+ return OC_STACK_ERROR;
+ }
}
void DefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
CAResult_t ret = CARegisterNetworkMonitorHandler(DefaultAdapterStateChangedHandler,
DefaultConnectionStateChangedHandler);
- switch (ret)
- {
- case CA_STATUS_OK:
- return OC_STACK_OK;
- case CA_NOT_SUPPORTED:
- return OC_STACK_NOTIMPL;
- default:
- return OC_STACK_ERROR;
- }
+ return convertCAResultToOCResult(ret);
+}
+
+OCStackResult CAManager::setPortNumberToAssign(OCTransportAdapter adapter,
+ OCTransportFlags flag, uint16_t port)
+{
+ CAResult_t ret = CASetPortNumberToAssign((CATransportAdapter_t) adapter,
+ (CATransportFlags_t) flag, port);
+
+ return convertCAResultToOCResult(ret);
+}
+
+uint16_t CAManager::getAssignedPortNumber(OCTransportAdapter adapter, OCTransportFlags flag)
+{
+ return CAGetAssignedPortNumber((CATransportAdapter_t) adapter, (CATransportFlags_t) flag);
}
// 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);
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);
}
InProcClientWrapper::~InProcClientWrapper()
{
- if(m_threadRun && m_listeningThread.joinable())
+ if (m_threadRun && m_listeningThread.joinable())
{
m_threadRun = false;
m_listeningThread.join();
// 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();
}
{
OCStackResult result;
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
std::lock_guard<std::recursive_mutex> lock(*cLock);
result = OCProcess();
result = OC_STACK_ERROR;
}
- if(result != OC_STACK_OK)
+ if (result != OC_STACK_OK)
{
// TODO: do something with result if failed?
}
OCRepresentation parseGetSetCallback(OCClientResponse* clientResponse)
{
- if(clientResponse->payload == nullptr ||
+ if (clientResponse->payload == nullptr ||
(
clientResponse->payload->type != PAYLOAD_TYPE_DEVICE &&
clientResponse->payload->type != PAYLOAD_TYPE_PLATFORM &&
//OCPayloadDestroy(clientResponse->payload);
std::vector<OCRepresentation>::const_iterator it = oc.representations().begin();
- if(it == oc.representations().end())
+ if (it == oc.representations().end())
{
return OCRepresentation();
}
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
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;
auto clientWrapper = context->clientWrapper.lock();
- if(!clientWrapper)
+ if (!clientWrapper)
{
oclog() << "listenCallback(): failed to get a shared_ptr to the client wrapper"
<< std::flush;
OCConnectivityType connectivityType,
FindCallback& callback, QualityOfService QoS)
{
- if(!callback)
+ if (!callback)
{
return OC_STACK_INVALID_PARAM;
}
ClientCallbackContext::ListenContext* context =
new ClientCallbackContext::ListenContext(callback, shared_from_this());
- OCCallbackData cbdata(
- static_cast<void*>(context),
- listenCallback,
- [](void* c){delete static_cast<ClientCallbackContext::ListenContext*>(c);}
- );
+ OCCallbackData cbdata;
+ cbdata.context = static_cast<void*>(context),
+ cbdata.cb = listenCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::ListenContext*)c;};
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
std::lock_guard<std::recursive_mutex> lock(*cLock);
result = OCDoResource(nullptr, OC_REST_DISCOVER,
FindDeviceCallback& callback,
QualityOfService QoS)
{
- if(!callback)
+ if (!callback)
{
return OC_STACK_INVALID_PARAM;
}
ClientCallbackContext::DeviceListenContext* context =
new ClientCallbackContext::DeviceListenContext(callback, shared_from_this());
- OCCallbackData cbdata(
- static_cast<void*>(context),
- listenDeviceCallback,
- [](void* c){delete static_cast<ClientCallbackContext::DeviceListenContext*>(c);}
- );
+ OCCallbackData cbdata;
+
+ cbdata.context = static_cast<void*>(context),
+ cbdata.cb = listenDeviceCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::DeviceListenContext*)c;};
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
std::lock_guard<std::recursive_mutex> lock(*cLock);
result = OCDoResource(nullptr, OC_REST_DISCOVER,
void parseServerHeaderOptions(OCClientResponse* clientResponse,
HeaderOptions& serverHeaderOptions)
{
- if(clientResponse)
+ if (clientResponse)
{
// Parse header options from server
uint16_t optionID;
OCRepresentation rep;
HeaderOptions serverHeaderOptions;
OCStackResult result = clientResponse->result;
- if(result == OC_STACK_OK)
+ if (result == OC_STACK_OK)
{
parseServerHeaderOptions(clientResponse, serverHeaderOptions);
try
const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
GetCallback& callback, QualityOfService QoS)
{
- if(!callback)
+ if (!callback)
{
return OC_STACK_INVALID_PARAM;
}
OCStackResult result;
ClientCallbackContext::GetContext* ctx =
new ClientCallbackContext::GetContext(callback);
- OCCallbackData cbdata(
- static_cast<void*>(ctx),
- getResourceCallback,
- [](void* c){delete static_cast<ClientCallbackContext::GetContext*>(c);}
- );
+ OCCallbackData cbdata;
+ cbdata.context = static_cast<void*>(ctx),
+ cbdata.cb = getResourceCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::GetContext*)c;};
+
std::string uri = assembleSetResourceUri(resourceUri, queryParams);
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
std::lock_guard<std::recursive_mutex> lock(*cLock);
OCHeaderOption options[MAX_HEADER_OPTIONS];
std::string InProcClientWrapper::assembleSetResourceUri(std::string uri,
const QueryParamsMap& queryParams)
{
- if(uri.back() == '/')
+ if (!uri.empty())
{
- uri.resize(uri.size()-1);
+ if (uri.back() == '/')
+ {
+ uri.resize(uri.size() - 1);
+ }
}
ostringstream paramsList;
- if(queryParams.size() > 0)
+ if (queryParams.size() > 0)
{
paramsList << '?';
}
- for(auto& param : queryParams)
+ for (auto& param : queryParams)
{
paramsList << param.first <<'='<<param.second<<';';
}
std::string queryString = paramsList.str();
- if(queryString.back() == ';')
+
+ if (queryString.empty())
+ {
+ return uri;
+ }
+
+ if (queryString.back() == ';')
{
queryString.resize(queryString.size() - 1);
}
const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
PostCallback& callback, QualityOfService QoS)
{
- if(!callback)
+ if (!callback)
{
return OC_STACK_INVALID_PARAM;
}
OCStackResult result;
ClientCallbackContext::SetContext* ctx = new ClientCallbackContext::SetContext(callback);
- OCCallbackData cbdata(
- static_cast<void*>(ctx),
- setResourceCallback,
- [](void* c){delete static_cast<ClientCallbackContext::SetContext*>(c);}
- );
+ OCCallbackData cbdata;
+ cbdata.context = static_cast<void*>(ctx),
+ cbdata.cb = setResourceCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::SetContext*)c;};
+
std::string url = assembleSetResourceUri(uri, queryParams);
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
std::lock_guard<std::recursive_mutex> lock(*cLock);
OCHeaderOption options[MAX_HEADER_OPTIONS];
const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
PutCallback& callback, QualityOfService QoS)
{
- if(!callback)
+ if (!callback)
{
return OC_STACK_INVALID_PARAM;
}
OCStackResult result;
ClientCallbackContext::SetContext* ctx = new ClientCallbackContext::SetContext(callback);
- OCCallbackData cbdata(
- static_cast<void*>(ctx),
- setResourceCallback,
- [](void* c){delete static_cast<ClientCallbackContext::SetContext*>(c);}
- );
+ OCCallbackData cbdata;
+ cbdata.context = static_cast<void*>(ctx),
+ cbdata.cb = setResourceCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::SetContext*)c;};
+
std::string url = assembleSetResourceUri(uri, queryParams).c_str();
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
std::lock_guard<std::recursive_mutex> lock(*cLock);
OCDoHandle handle;
static_cast<ClientCallbackContext::DeleteContext*>(ctx);
HeaderOptions serverHeaderOptions;
- if(clientResponse->result == OC_STACK_OK)
+ if (clientResponse->result == OC_STACK_OK)
{
parseServerHeaderOptions(clientResponse, serverHeaderOptions);
}
DeleteCallback& callback,
QualityOfService /*QoS*/)
{
- if(!callback)
+ if (!callback)
{
return OC_STACK_INVALID_PARAM;
}
OCStackResult result;
ClientCallbackContext::DeleteContext* ctx =
new ClientCallbackContext::DeleteContext(callback);
- OCCallbackData cbdata(
- static_cast<void*>(ctx),
- deleteResourceCallback,
- [](void* c){delete static_cast<ClientCallbackContext::DeleteContext*>(c);}
- );
+ OCCallbackData cbdata;
+ cbdata.context = static_cast<void*>(ctx),
+ cbdata.cb = deleteResourceCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::DeleteContext*)c;};
+
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
OCHeaderOption options[MAX_HEADER_OPTIONS];
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
std::thread exec(context->callback, serverHeaderOptions, attrs,
result, sequenceNumber);
exec.detach();
- if(sequenceNumber == OC_OBSERVE_DEREGISTER)
+ if (sequenceNumber == OC_OBSERVE_DEREGISTER)
{
return OC_STACK_DELETE_TRANSACTION;
}
const QueryParamsMap& queryParams, const HeaderOptions& headerOptions,
ObserveCallback& callback, QualityOfService QoS)
{
- if(!callback)
+ if (!callback)
{
return OC_STACK_INVALID_PARAM;
}
ClientCallbackContext::ObserveContext* ctx =
new ClientCallbackContext::ObserveContext(callback);
- OCCallbackData cbdata(
- static_cast<void*>(ctx),
- observeResourceCallback,
- [](void* c){delete static_cast<ClientCallbackContext::ObserveContext*>(c);}
- );
+ OCCallbackData cbdata;
+ cbdata.context = static_cast<void*>(ctx),
+ cbdata.cb = observeResourceCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::ObserveContext*)c;};
+
OCMethod method;
if (observeType == ObserveType::Observe)
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
std::lock_guard<std::recursive_mutex> lock(*cLock);
OCHeaderOption options[MAX_HEADER_OPTIONS];
OCStackResult result;
auto cLock = m_csdkLock.lock();
- if(cLock)
+ if (cLock)
{
std::lock_guard<std::recursive_mutex> lock(*cLock);
OCHeaderOption options[MAX_HEADER_OPTIONS];
const std::string& host, const std::string& resourceType,
OCConnectivityType connectivityType, SubscribeCallback& presenceHandler)
{
- if(!presenceHandler)
+ if (!presenceHandler)
{
return OC_STACK_INVALID_PARAM;
}
ClientCallbackContext::SubscribePresenceContext* ctx =
new ClientCallbackContext::SubscribePresenceContext(presenceHandler);
- OCCallbackData cbdata(
- static_cast<void*>(ctx),
- subscribePresenceCallback,
- [](void* c)
- {delete static_cast<ClientCallbackContext::SubscribePresenceContext*>(c);}
- );
+ OCCallbackData cbdata;
+ cbdata.context = static_cast<void*>(ctx),
+ cbdata.cb = subscribePresenceCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::SubscribePresenceContext*)c;};
+
auto cLock = m_csdkLock.lock();
std::ostringstream os;
os << host << OC_RSRVD_PRESENCE_URI;
- if(!resourceType.empty())
+ if (!resourceType.empty())
{
os << "?rt=" << resourceType;
}
- if(!cLock)
+ if (!cLock)
{
delete ctx;
return OC_STACK_ERROR;
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);
{
int i = 0;
- if( headerOptions.size() == 0)
+ if ( headerOptions.size() == 0)
{
return nullptr;
}
for (auto it=headerOptions.begin(); it != headerOptions.end(); ++it)
{
- options[i] = OCHeaderOption(OC_COAP_ID,
- it->getOptionID(),
- it->getOptionData().length() + 1,
- reinterpret_cast<const uint8_t*>(it->getOptionData().c_str()));
+ options[i] = OCHeaderOption();
+ options[i].protocolID = OC_COAP_ID;
+ options[i].optionID = it->getOptionID();
+ options[i].optionLength = it->getOptionData().length() + 1;
+ strcpy((char*)options[i].optionData, (it->getOptionData().c_str()));
i++;
}
return options;
}
+
+ std::shared_ptr<OCDirectPairing> cloneDevice(const OCDPDev_t* dev)
+ {
+ if (!dev)
+ {
+ return nullptr;
+ }
+
+ OCDPDev_t* result = new OCDPDev_t(*dev);
+ result->prm = new OCPrm_t[dev->prmLen];
+ memcpy(result->prm, dev->prm, sizeof(OCPrm_t)*dev->prmLen);
+ return std::shared_ptr<OCDirectPairing>(new OCDirectPairing(result));
+ }
+
+ void InProcClientWrapper::convert(const OCDPDev_t *list, PairedDevices& dpList)
+ {
+ while(list)
+ {
+ dpList.push_back(cloneDevice(list));
+ list = list->next;
+ }
+ }
+
+ OCStackResult InProcClientWrapper::FindDirectPairingDevices(unsigned short waittime,
+ GetDirectPairedCallback& callback)
+ {
+ if (!callback || 0 == waittime)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult result = OC_STACK_ERROR;
+ const OCDPDev_t *list = nullptr;
+ PairedDevices dpDeviceList;
+
+ auto cLock = m_csdkLock.lock();
+
+ if (cLock)
+ {
+ std::lock_guard<std::recursive_mutex> lock(*cLock);
+
+ list = OCDiscoverDirectPairingDevices(waittime);
+ if (NULL == list)
+ {
+ result = OC_STACK_NO_RESOURCE;
+ oclog() << "findDirectPairingDevices(): No device found for direct pairing"
+ << std::flush;
+ }
+ else {
+ convert(list, dpDeviceList);
+ std::thread exec(callback, dpDeviceList);
+ exec.detach();
+ result = OC_STACK_OK;
+ }
+ }
+ else
+ {
+ result = OC_STACK_ERROR;
+ }
+
+ return result;
+ }
+
+ OCStackResult InProcClientWrapper::GetDirectPairedDevices(GetDirectPairedCallback& callback)
+ {
+ if (!callback)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult result = OC_STACK_ERROR;
+ const OCDPDev_t *list = nullptr;
+ PairedDevices dpDeviceList;
+
+ auto cLock = m_csdkLock.lock();
+
+ if (cLock)
+ {
+ std::lock_guard<std::recursive_mutex> lock(*cLock);
+
+ list = OCGetDirectPairedDevices();
+ if (NULL == list)
+ {
+ result = OC_STACK_NO_RESOURCE;
+ oclog() << "findDirectPairingDevices(): No device found for direct pairing"
+ << std::flush;
+ }
+ else {
+ convert(list, dpDeviceList);
+ std::thread exec(callback, dpDeviceList);
+ exec.detach();
+ result = OC_STACK_OK;
+ }
+ }
+ else
+ {
+ result = OC_STACK_ERROR;
+ }
+
+ return result;
+ }
+
+ void directPairingCallback(void *ctx, OCDPDev_t *peer,
+ OCStackResult result)
+ {
+
+ ClientCallbackContext::DirectPairingContext* context =
+ static_cast<ClientCallbackContext::DirectPairingContext*>(ctx);
+
+ std::thread exec(context->callback, cloneDevice(peer), result);
+ exec.detach();
+ }
+
+ OCStackResult InProcClientWrapper::DoDirectPairing(std::shared_ptr<OCDirectPairing> peer,
+ const OCPrm_t& pmSel, const std::string& pinNumber, DirectPairingCallback& callback)
+ {
+ if (!peer || !callback)
+ {
+ oclog() << "Invalid parameters" << std::flush;
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult result = OC_STACK_ERROR;
+ ClientCallbackContext::DirectPairingContext* context =
+ new ClientCallbackContext::DirectPairingContext(callback);
+
+ auto cLock = m_csdkLock.lock();
+ if (cLock)
+ {
+ std::lock_guard<std::recursive_mutex> lock(*cLock);
+ result = OCDoDirectPairing(static_cast<void*>(context), peer->getDev(),
+ pmSel, const_cast<char*>(pinNumber.c_str()), directPairingCallback);
+ }
+ else
+ {
+ delete context;
+ result = OC_STACK_ERROR;
+ }
+ return result;
+ }
}
std::mutex serverWrapperLock;
std::map <OCResourceHandle, OC::EntityHandler> entityHandlerMap;
std::map <OCResourceHandle, std::string> resourceUriMap;
- EntityHandler defaultDeviceEntityHandler = 0;
+ EntityHandler defaultDeviceEntityHandler;
}
}
{
pRequest->setRequestHandle(entityHandlerRequest->requestHandle);
pRequest->setResourceHandle(entityHandlerRequest->resource);
+ pRequest->setMessageID(entityHandlerRequest->messageID);
}
if(flag & OC_REQUEST_FLAG)
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#include "ocapi.h"
+#include "OCApi.h"
+
+#if defined(_MSC_VER)
+namespace OC
+{
+ std::ostream& oclog()
+ {
+ return std::cout;
+ }
+}
+#endif
--- /dev/null
+//******************************************************************
+//
+// 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;
+ }
+}
return OC::Exception::INVALID_REPRESENTATION;
case OC_STACK_UNAUTHORIZED_REQ:
return OC::Exception::UNAUTHORIZED_REQUEST;
+ case OC_STACK_TOO_LARGE_REQ:
+ return OC::Exception::TOO_LARGE_REQ;
case OC_STACK_PDM_IS_NOT_INITIALIZED:
return OC::Exception::PDM_DB_NOT_INITIALIZED;
case OC_STACK_DUPLICATE_UUID:
}
OCStackResult notifyAllObservers(OCResourceHandle resourceHandle,
- QualityOfService QoS)
+ QualityOfService QoS)
{
return OCPlatform_impl::Instance().notifyAllObservers(resourceHandle, QoS);
}
}
OCStackResult notifyListOfObservers(OCResourceHandle resourceHandle,
- ObservationIds& observationIds,
- const std::shared_ptr<OCResourceResponse> pResponse)
+ ObservationIds& observationIds,
+ const std::shared_ptr<OCResourceResponse> pResponse)
{
return OCPlatform_impl::Instance().notifyListOfObservers(resourceHandle,
- observationIds, pResponse);
+ observationIds, pResponse);
}
OCStackResult notifyListOfObservers(OCResourceHandle resourceHandle,
- ObservationIds& observationIds,
- const std::shared_ptr<OCResourceResponse> pResponse,
- QualityOfService QoS)
+ ObservationIds& observationIds,
+ const std::shared_ptr<OCResourceResponse> pResponse,
+ QualityOfService QoS)
{
return OCPlatform_impl::Instance().notifyListOfObservers(resourceHandle,
- observationIds, pResponse, QoS);
+ observationIds, pResponse, QoS);
}
OCResource::Ptr constructResourceObject(const std::string& host,
- const std::string& uri,
- OCConnectivityType connectivityType,
- bool isObservable,
- const std::vector<std::string>& resourceTypes,
- const std::vector<std::string>& interfaces)
+ const std::string& uri,
+ OCConnectivityType connectivityType,
+ bool isObservable,
+ const std::vector<std::string>& resourceTypes,
+ const std::vector<std::string>& interfaces)
{
return OCPlatform_impl::Instance().constructResourceObject(host,
- uri, connectivityType,
- isObservable,
- resourceTypes, interfaces);
+ uri, connectivityType,
+ isObservable,
+ resourceTypes, interfaces);
}
OCStackResult findResource(const std::string& host,
- const std::string& resourceName,
- OCConnectivityType connectivityType,
- FindCallback resourceHandler)
+ const std::string& resourceName,
+ OCConnectivityType connectivityType,
+ FindCallback resourceHandler)
{
return OCPlatform_impl::Instance().findResource(host, resourceName,
- connectivityType, resourceHandler);
+ connectivityType, resourceHandler);
}
OCStackResult findResource(const std::string& host,
- const std::string& resourceName,
- OCConnectivityType connectivityType,
- FindCallback resourceHandler,
- QualityOfService QoS)
+ const std::string& resourceName,
+ OCConnectivityType connectivityType,
+ FindCallback resourceHandler,
+ QualityOfService QoS)
{
return OCPlatform_impl::Instance().findResource(host, resourceName,
- connectivityType, resourceHandler, QoS);
+ connectivityType, resourceHandler, QoS);
}
OCStackResult findResource(const std::string& host,
}
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);
}
}
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)
}
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)
{
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
{
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
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);
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)
{
((int64_t*)array)[pos] = item;
}
+#if !defined(_MSC_VER)
template<>
void get_payload_array::copy_to_array(std::_Bit_reference br, void* array, size_t pos)
{
((bool*)array)[pos] = static_cast<bool>(br);
}
+#endif
template<>
void get_payload_array::copy_to_array(std::string item, void* array, size_t pos)
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();
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;
}
// contains the inner most vector-type
typedef T base_type;
// contains the AttributeType for this item
- constexpr static AttributeType enum_type =
+ BOOST_STATIC_CONSTEXPR AttributeType enum_type =
AttributeTypeConvert<T>::type;
// contains the AttributeType for this base-type
- constexpr static AttributeType enum_base_type =
+ BOOST_STATIC_CONSTEXPR AttributeType enum_base_type =
AttributeTypeConvert<T>::type;
// depth of the vector
- constexpr static size_t depth = 0;
+ BOOST_STATIC_CONSTEXPR size_t depth = 0;
};
template<typename T>
{
typedef T type;
typedef typename type_info<typename T::value_type>::base_type base_type;
- constexpr static AttributeType enum_type = AttributeType::Vector;
- constexpr static AttributeType enum_base_type =
+ BOOST_STATIC_CONSTEXPR AttributeType enum_type = AttributeType::Vector;
+ BOOST_STATIC_CONSTEXPR AttributeType enum_base_type =
type_info<typename T::value_type>::enum_base_type;
- constexpr static size_t depth = 1 +
+ BOOST_STATIC_CONSTEXPR size_t depth = 1 +
type_info<typename T::value_type>::depth;
};
{
typedef std::vector<uint8_t> type;
typedef std::vector<uint8_t> base_type;
- constexpr static AttributeType enum_type = AttributeType::Binary;
- constexpr static AttributeType enum_base_type = AttributeType::Binary;
- constexpr static size_t depth = 0;
+ BOOST_STATIC_CONSTEXPR AttributeType enum_type = AttributeType::Binary;
+ BOOST_STATIC_CONSTEXPR AttributeType enum_base_type = AttributeType::Binary;
+ BOOST_STATIC_CONSTEXPR size_t depth = 0;
};
#include <boost/lexical_cast.hpp>
#include <sstream>
+#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_IN6ADDR_H
+#include <in6addr.h>
+#endif
namespace OC {
static const char COAP[] = "coap://";
static const char COAPS[] = "coaps://";
static const char COAP_TCP[] = "coap+tcp://";
+static const char COAP_GATT[] = "coap+gatt://";
+static const char COAP_RFCOMM[] = "coap+rfcomm://";
using OC::nil_guard;
using OC::result_guard;
const std::vector<std::string>& interfaces)
: m_clientWrapper(clientWrapper), m_uri(uri),
m_resourceId(serverId, m_uri),
- m_devAddr{ OC_DEFAULT_ADAPTER, OC_DEFAULT_FLAGS, 0, {0}, 0
-#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
- , {0}
-#endif
- },
m_isObservable(observable), m_isCollection(false),
m_resourceTypes(resourceTypes), m_interfaces(interfaces),
m_observeHandle(nullptr)
{
+ m_devAddr = OCDevAddr{OC_DEFAULT_ADAPTER, OC_DEFAULT_FLAGS, 0, {0}, 0,
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
+ {0}
+#endif
+ };
m_isCollection = std::find(m_interfaces.begin(), m_interfaces.end(), LINK_INTERFACE)
!= m_interfaces.end();
else if(host.compare(0, sizeof(COAPS) - 1, COAPS) == 0)
{
prefix_len = sizeof(COAPS) - 1;
- m_devAddr.flags = static_cast<OCTransportFlags>(m_devAddr.flags & OC_SECURE);
+ m_devAddr.flags = static_cast<OCTransportFlags>(m_devAddr.flags | OC_SECURE);
}
else if (host.compare(0, sizeof(COAP_TCP) - 1, COAP_TCP) == 0)
{
prefix_len = sizeof(COAP_TCP) - 1;
}
+ else if (host.compare(0, sizeof(COAP_GATT) - 1, COAP_GATT) == 0)
+ {
+ prefix_len = sizeof(COAP_GATT) - 1;
+ }
+ else if (host.compare(0, sizeof(COAP_RFCOMM) - 1, COAP_RFCOMM) == 0)
+ {
+ prefix_len = sizeof(COAP_RFCOMM) - 1;
+ }
else
{
throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
m_interfaces.empty(), m_clientWrapper.expired(), false, false);
}
- // remove 'coap://' or 'coaps://' or 'coap+tcp://'
+ // remove 'coap://' or 'coaps://' or 'coap+tcp://' or 'coap+gatt://' or 'coap+rfcomm://'
std::string host_token = host.substr(prefix_len);
if(host_token[0] == '[') // IPv6
OCStackResult result = checked_guard(m_clientWrapper.lock(),
&IClientWrapper::CancelObserveResource,
- m_observeHandle, "", m_uri, m_headerOptions, QoS);
+ m_observeHandle, (const char*)"", m_uri, m_headerOptions, QoS);
if(result == OC_STACK_OK)
{
std::string OCResource::host() const
{
std::ostringstream ss;
- if (m_devAddr.flags & OC_SECURE)
+
+ if (m_devAddr.adapter & OC_ADAPTER_TCP)
{
- ss << COAPS;
+ ss << COAP_TCP;
}
- else if ((m_devAddr.adapter & OC_ADAPTER_TCP)
- || (m_devAddr.adapter & OC_ADAPTER_GATT_BTLE)
- || (m_devAddr.adapter & OC_ADAPTER_RFCOMM_BTEDR))
+ else if (m_devAddr.adapter & OC_ADAPTER_GATT_BTLE)
{
- ss << COAP_TCP;
+ ss << COAP_GATT;
+ }
+ else if (m_devAddr.adapter & OC_ADAPTER_RFCOMM_BTEDR)
+ {
+ ss << COAP_RFCOMM;
}
else
{
- ss << COAP;
+ if (m_devAddr.flags & OC_SECURE)
+ {
+ ss << COAPS;
+ }
+ else
+ {
+ ss << COAP;
+ }
}
+
if (m_devAddr.flags & OC_IP_USE_V6)
{
ss << '[' << m_devAddr.addr << ']';
##
Import('env')
+import os
+
# Add third party libraries
lib_env = env.Clone()
SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env')
oclib_env = lib_env.Clone()
+secured = lib_env.get('SECURED')
######################################################################
# Build flags
######################################################################
oclib_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-oclib_env.AppendUnique(LIBS = ['octbstack', 'oc_logger'])
-oclib_env.AppendUnique(LIBS = ['connectivity_abstraction'])
+oclib_env.AppendUnique(LIBS = ['oc_logger'])
+oclib_env.PrependUnique(LIBS = ['octbstack', 'connectivity_abstraction', 'ocsrm'])
target_os = env.get('TARGET_OS')
if target_os == 'linux':
oclib_env.AppendUnique(LIBS = ['pthread'])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
oclib_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-fPIC'])
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
oclib_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
if target_os == 'android':
if target_os in ['linux'] and env.get('SIMULATOR', False):
oclib_env.Append( RPATH = env.Literal('\\$$ORIGIN'))
+if target_os in ['msys_nt', 'windows']:
+ oclib_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'oc_logger')])
+ oclib_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk')])
+ oclib_env.AppendUnique(LIBS=['octbstack', 'logger', 'oc_logger','connectivity_abstraction', 'ocsrm', 'c_common', 'routingmanager'])
+ oclib_env.AppendUnique(LIBS=[ 'coap', 'ws2_32' ,'iphlpapi'])
+ if secured == '1':
+ oclib_env.AppendUnique(LIBS=['tinydtls'])
+
######################################################################
# Source files and Targets
######################################################################
'InProcServerWrapper.cpp',
'InProcClientWrapper.cpp',
'OCResourceRequest.cpp',
- 'CAManager.cpp'
+ 'CAManager.cpp',
+ 'OCDirectPairing.cpp'
]
-oclib = oclib_env.SharedLibrary('oc', oclib_src)
-oclib_env.InstallTarget(oclib, 'liboc')
-oclib_env.UserInstallTargetLib(oclib, 'liboc')
-
+if target_os in ['windows']:
+ oclib_src = oclib_src + ['OCApi.cpp']
+ # TODO: Add OC_EXPORT prefixes to enable DLL generation
+ oclib = oclib_env.StaticLibrary('oc', oclib_src)
+else:
+ oclib = oclib_env.SharedLibrary('oc', oclib_src)
+oclib_env.InstallTarget(oclib, 'oc')
+oclib_env.UserInstallTargetLib(oclib, 'oc')
header_dir = env.get('SRC_DIR') + '/resource/include/'
oclib_env.UserInstallTargetHeader(header_dir + 'OCApi.h', 'resource', 'OCApi.h')
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':
# Too much boost warning, suppress the warning
lib_env.AppendUnique(CCFLAGS = ['-w'])
+elif target_os in ['windows']:
+ SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'boost', 'SConscript'))
+ boost_path = os.path.join(src_dir,'extlibs','boost','boost')
+ lib_env.AppendUnique(CPPPATH = [boost_path])
elif target_os == 'ios':
lib_env.AppendUnique(FRAMEWORKS = ['boost'])
elif target_os == 'darwin':
SConscript('csdk/security/provisioning/unittest/SConscript')
SConscript('provisioning/unittests/SConscript')
-elif target_os == 'darwin':
+elif target_os == 'windows' and env.get('TEST') == '1':
# Verify that 'google unit test' library is installed. If not,
# get it and install it
SConscript(src_dir + '/extlibs/gtest/SConscript')
SConscript('csdk/stack/test/SConscript')
SConscript('csdk/connectivity/test/SConscript')
+ # Build Security Resource Manager unit tests
+ SConscript('csdk/security/unittest/SConscript')
+ # Build Provisioning API unit test
+ if env.get('SECURED') == '1':
+ SConscript('csdk/security/provisioning/unittest/SConscript')
+
+elif target_os in ['darwin', 'msys_nt']:
+ # Verify that 'google unit test' library is installed. If not,
+ # get it and install it
+ SConscript(src_dir + '/extlibs/gtest/SConscript')
+
+ # Build C stack's unit tests.
+ SConscript('csdk/stack/test/SConscript')
+ SConscript('csdk/connectivity/test/SConscript')
OC_STACK_INVALID_DEVICE_INFO,
OC_STACK_INVALID_JSON,
OC_STACK_UNAUTHORIZED_REQ,
+ OC_STACK_TOO_LARGE_REQ,
OC_STACK_PRESENCE_STOPPED,
OC_STACK_PRESENCE_TIMEOUT,
OC_STACK_PRESENCE_DO_NOT_HANDLE,
OC::Exception::INVALID_DEVICE_INFO,
OC::Exception::INVALID_REPRESENTATION,
OC::Exception::UNAUTHORIZED_REQUEST,
+ OC::Exception::TOO_LARGE_REQ,
OC::Exception::PRESENCE_STOPPED,
OC::Exception::PRESENCE_TIMEOUT,
OC::Exception::PRESENCE_NOT_HANDLED,
{
}
+ void directPairHandler(std::shared_ptr<OCDirectPairing> /*dev*/, OCStackResult /*res*/)
+ {
+ }
+
+ void pairedHandler(const PairedDevices& /*list*/)
+ {
+ }
+
//Helper methods
void DeleteStringLL(OCStringLL* ll)
{
{
delete[] deviceInfo.deviceName;
DeleteStringLL(deviceInfo.types);
-
+ delete[] deviceInfo.specVersion;
+ DeleteStringLL(deviceInfo.dataModelVersions);
}
void DuplicateString(char ** targetString, std::string sourceString)
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));
}
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));
+ }
}
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)
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);
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);
}
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;
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);
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)
--- /dev/null
+@echo off
+REM Helper script to build and run IoTivity on Windows
+SETLOCAL ENABLEDELAYEDEXPANSION
+
+if [%1]==[] goto USAGE
+
+set IOTIVITY_DIR=%~dp0
+set HOME=%USERPROFILE%
+
+IF "%1" == "msys" (
+ set BUILD_MSYS="YES"
+ SHIFT
+) ELSE (
+ set BUILD_MSYS=
+)
+
+set CURRENT_ARG=%1
+set SECOND_ARG=%2
+set DEBUG=
+
+if "!SECOND_ARG!"=="debug" (
+ set DEBUG="%ProgramFiles(x86)%\Windows Kits\10\Debuggers\x64\cdb.exe" -2 -c "g"
+)
+
+IF "%BUILD_MSYS%" == "" (
+ IF NOT "%VS140COMNTOOLS%" == "" (
+ CALL "%VS140COMNTOOLS%"vsvars32.bat
+ ) ELSE (
+ IF NOT "%VS120COMNTOOLS%" == "" (
+ CALL "%VS120COMNTOOLS%"vsvars32.bat
+ )
+ )
+
+ IF NOT "!VSINSTALLDIR!" == "" (
+ CALL "!VSINSTALLDIR!VC\vcvarsall.bat" amd64
+ ) ELSE (
+ @ECHO WARNING: Could not find vsvarsall.bat.
+ @ECHO WARNING: VISUAL STUDIO 2013/2015 DOES NOT APPEAR TO BE INSTALLED ON THIS MACHINE
+ GOTO :EOF
+ )
+)
+
+REM We need to append the "PATH" so the octbstack.dll can be found by executables
+IF "%BUILD_MSYS%" == "" (
+ set BUILD_DIR=out\windows\amd64\debug
+ set PATH=!PATH!;!BUILD_DIR!;
+) ELSE (
+ set BUILD_DIR=out\msys_nt\x86_64\debug
+ set PATH=!PATH!;!BUILD_DIR!;C:\msys64\mingw64\bin
+)
+
+REM *** BUILD OPTIONS ***
+set TARGET_OS=windows
+set TARGET_ARCH=amd64
+set SECURED=1
+set TEST=1
+set LOGGING=OFF
+set WITH_RD=1
+REM *** BUILD OPTIONS ***
+
+if "!CURRENT_ARG!"=="server" (
+ %DEBUG% %BUILD_DIR%\resource\examples\simpleserver.exe
+) else if "!CURRENT_ARG!"=="client" (
+ %DEBUG% %BUILD_DIR%\resource\examples\simpleclient.exe
+) else if "!CURRENT_ARG!"=="mediaclient" (
+ %DEBUG% %BUILD_DIR%\debug\resource\examples\mediaclient.exe
+) else if "!CURRENT_ARG!"=="mediaserver" (
+ %DEBUG% %BUILD_DIR%\resource\examples\mediaserver.exe
+) else if "!CURRENT_ARG!"=="winuiclient" (
+ %DEBUG% %BUILD_DIR%\resource\examples\winuiclient.exe
+) else if "!CURRENT_ARG!"=="occlient" (
+ %DEBUG% %BUILD_DIR%\resource\csdk\stack\samples\linux\SimpleClientServer\occlientbasicops.exe -u 0 -t 3 -c 1
+) else if "!CURRENT_ARG!"=="ocserver" (
+ %DEBUG% %BUILD_DIR%\resource\csdk\stack\samples\linux\SimpleClientServer\ocserverbasicops.exe
+) else if "!CURRENT_ARG!"=="test" (
+ %DEBUG% %BUILD_DIR%\resource\csdk\connectivity\test\catests.exe
+ %DEBUG% %BUILD_DIR%\resource\csdk\stack\test\stacktests.exe
+ %DEBUG% %BUILD_DIR%\resource\csdk\stack\test\cbortests.exe
+ %DEBUG% %BUILD_DIR%\resource\csdk\security\unittest\unittest.exe
+ %DEBUG% %BUILD_DIR%\resource\csdk\security\provisioning\unittest\unittest.exe
+) else if "!CURRENT_ARG!"=="build" (
+ echo Starting IoTivity build with these options:
+ echo TARGET_OS=%TARGET_OS%
+ echo TARGET_ARCH=%TARGET_ARCH%
+ echo SECURED=%SECURED%
+ echo LOGGING=%LOGGING%
+ echo WITH_RD=%WITH_RD%
+ CL.exe | findstr "Compiler Verison"
+ echo.scons VERBOSE=1 TARGET_OS=%TARGET_OS% TARGET_ARCH=%TARGET_ARCH% RELEASE=0 WITH_RA=0 TARGET_TRANSPORT=IP SECURED=%SECURED% WITH_TCP=0 BUILD_SAMPLE=ON LOGGING=%LOGGING% TEST=%TEST% WITH_RD=%WITH_RD%
+ scons VERBOSE=1 TARGET_OS=%TARGET_OS% TARGET_ARCH=%TARGET_ARCH% RELEASE=0 WITH_RA=0 TARGET_TRANSPORT=IP SECURED=%SECURED% WITH_TCP=0 BUILD_SAMPLE=ON LOGGING=%LOGGING% TEST=%TEST% WITH_RD=%WITH_RD%
+) else if "!CURRENT_ARG!"=="clean" (
+ scons VERBOSE=1 TARGET_OS=%TARGET_OS% TARGET_ARCH=%TARGET_ARCH% RELEASE=0 WITH_RA=0 TARGET_TRANSPORT=IP SECURED=%SECURED% WITH_TCP=0 BUILD_SAMPLE=ON LOGGING=%LOGGING% TEST=%TEST% WITH_RD=%WITH_RD% -c clean
+ rd /s /q out
+ del .sconsign.dblite
+) else if "!CURRENT_ARG!"=="cleangtest" (
+ rd /s /q extlibs\gtest\gtest-1.7.0
+ del extlibs\gtest\gtest-1.7.0.zip
+) else (
+ echo %0 - Script requires a valid argument!
+ goto :EOF
+)
+
+echo Done!
+
+goto EOF
+
+:USAGE
+echo %0 - Helper to build/test iotivity. Requires an argument.
+echo Installation: Drop this into your iotivity root directory to use it.
+echo.
+echo. Usage examples:
+echo Launch SimpleClient with debugger:
+echo %0 client debug
+echo.
+echo Launch SimpleServer:
+echo %0 server
+echo.
+echo Launch WinUIClient built in msys:
+echo %0 msys winuiclient
+echo.
+echo Build:
+echo %0 build
+echo.
+echo Run all tests:
+echo %0 test
+echo.
+echo Clean:
+echo %0 clean
+
+:EOF
# Update the new environment, usually include add header file paths,
# library path, libs to link and other compiler flags. This part is
# optional.
- new_env.AppeneUnique(xxx = [ .... ])
+ new_env.AppendUnique(xxx = [ .... ])
# Specify the target(application, library, object or others) to build
ts = new_env.Program('progam_name', [source_list])
target_os = env.get('TARGET_OS')
-if target_os not in ['arduino','darwin', 'ios']:
+if target_os not in ['arduino','darwin', 'ios', 'windows']:
# Build things manager project
SConscript('things-manager/SConscript')
if target_os in ['linux'] and env.get('SIMULATOR', False):
SConscript('simulator/SConscript')
- # Build resource directory project
- if env.get('WITH_RD') == '1':
- SConscript('resource-directory/SConscript')
+# Build resource directory project
+if env.get('WITH_RD') == '1':
+ SConscript('resource-directory/SConscript')
# Build EasySetup module
if target_os in ['arduino', 'android', 'linux','tizen']:
enrollee_env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal',
enrollee_env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/oxm'])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
enrollee_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
######################################################################
'../../../inc',
])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
mediator_csdk_test_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
if target_os != 'android':
mediator_csdk_test_env.AppendUnique(CXXFLAGS = ['-pthread'])
target_os = env.get('TARGET_OS')
if target_os == 'linux':
from tools.scons.RunTest import *
- run_test(mediator_csdk_test_env, '', 'service/easy-setup/mediator/csdk/unittests/mediator_csdk_test')
\ No newline at end of file
+ run_test(mediator_csdk_test_env, '', 'service/easy-setup/mediator/csdk/unittests/mediator_csdk_test')
######################################################################
easy_setup_env.AppendUnique(CPPPATH = ['inc', 'src', '../../inc'])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
easy_setup_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
if target_os in ['linux']:
$(LOCAL_PATH)/../../../../../../resource/include \
$(LOCAL_PATH)/../../../../../../resource/c_common \
$(LOCAL_PATH)/../../../../../../resource/oc_logger/include \
- $(LOCAL_PATH)/../../../../../../resource/csdk/ocmalloc/include \
+ $(LOCAL_PATH)/../../../../../../resource/c_common/oic_malloc/include \
$(LOCAL_PATH)/../../../../../../resource/csdk/connectivity/api \
$(LOCAL_PATH)/../../../../../../resource/csdk/stack/include \
$(LOCAL_PATH)/../../../../../../resource/csdk/logger/include \
'../../../inc',
])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
mediator_rich_test_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
if target_os != 'android':
mediator_rich_test_env.AppendUnique(CXXFLAGS = ['-pthread'])
# Map of host os and allowed target os (host: allowed target os)
host_target_map = {
'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
- 'windows': ['windows', 'winrt', 'android', 'arduino', 'tizen'],
+ 'windows': ['windows', 'android', 'arduino', 'tizen'],
'darwin': ['darwin', 'ios', 'android', 'arduino'],
}
'linux': ['x86', 'x86_64', 'arm', 'arm64'],
'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
'windows': ['x86', 'amd64', 'arm'],
- 'winrt': ['arm'],
'darwin': ['i386', 'x86_64'],
'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
'arduino': ['avr', 'arm'],
# Map of host os and allowed target os (host: allowed target os)
host_target_map = {
'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
- 'windows': ['windows', 'winrt', 'android', 'arduino'],
+ 'windows': ['windows', 'android', 'arduino'],
'darwin': ['darwin', 'ios', 'android', 'arduino'],
}
'tizen': ['x86', 'x86_64', 'arm', 'arm64'],
'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
'windows': ['x86', 'amd64', 'arm'],
- 'winrt': ['arm'],
'darwin': ['i386', 'x86_64'],
'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
'arduino': ['avr', 'arm'],
%define ROOTDIR %{_builddir}/%{name}-%{version}
Name: com-oic-es-sample
-Version: 0.1
-Release: 1
+Version: 1.1.1
+Release: 0
Summary: Tizen adapter interfacesample application
URL: http://slp-source.sec.samsung.net
Source: %{name}-%{version}.tar.gz
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
},\r
{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
- "href": "/oic/res/types/d",\r
+ "href": "/oic/ad",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.ad"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
- "href": "/oic/ad",\r
+ "href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
- "href": "/oic/sec/acl",\r
+ "href": "/oic/res/types/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } ,\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
"deviceuuid": "61646d69-6e44-6576-6963-655575696430",\r
"devowneruuid": "61646d69-6e44-6576-6963-655575696430",\r
"rowneruuid": "61646d69-6e44-6576-6963-655575696430",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
}\r
}\r
mediator_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
mediator_env.PrependUnique(CPPPATH = [
- env.get('SRC_DIR') + '/resource/csdk/ocmalloc/include',
+ env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',
env.get('SRC_DIR') + '/resource/csdk/connectivity/common/inc',
env.get('SRC_DIR') + '/resource/csdk/connectivity/api',
env.get('SRC_DIR') + '/resource/csdk/stack/include',
env.AppendUnique(CPPDEFINES = ['CPP_MEDIATOR'])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
mediator_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
mediator_env.PrependUnique(CPPPATH = [
env.get('SRC_DIR') + '/resource/include',
env.get('SRC_DIR') + '/resource/oc_logger/include',
- env.get('SRC_DIR') + '/resource/csdk/ocmalloc/include',
+ env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',
env.get('SRC_DIR') + '/resource/csdk/stack/include',
env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include',
env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal',
print ''
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
resource_container_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
if target_os != 'android':
resource_container_env.AppendUnique(CXXFLAGS = ['-pthread'])
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
resource_container_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
if target_os == 'android':
#include "BMISensor.h"
#include <iostream>
-#include <stdlib.h>
+#include <cmath>
+#include <cstdlib>
#include "SysTimer.h"
#ifdef __ANDROID__
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)
const RCSResourceAttributes &value,
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
BundleResource::setAttributes(value);
}
RCSResourceAttributes BMISensorResource::handleGetAttributesRequest(const
std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
return BundleResource::getAttributes();
}
linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-linux_sample_env.AppendUnique(LIBS = ['libcoap'])
-linux_sample_env.AppendUnique(LIBS = ['libconnectivity_abstraction'])
-linux_sample_env.AppendUnique(LIBS = ['liboc_logger'])
+linux_sample_env.AppendUnique(LIBS = ['coap'])
+linux_sample_env.AppendUnique(LIBS = ['connectivity_abstraction'])
+linux_sample_env.AppendUnique(LIBS = ['oc_logger'])
linux_sample_env.AppendUnique(LIBS = ['octbstack'])
linux_sample_env.AppendUnique(LIBS = ['oc'])
linux_sample_env.AppendUnique(LIBS = ['pthread'])
const RCSResourceAttributes &value,
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
BundleResource::setAttributes(value);
}
RCSResourceAttributes DiscomfortIndexSensorResource::handleGetAttributesRequest(
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
return BundleResource::getAttributes();
}
#ifndef CONFIGURATION_H_
#define CONFIGURATION_H_
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_STRING_H
#include <string.h>
+#endif
#include <iostream>
#include <fstream>
#include <string>
virtual void handleSetAttributesRequest(const RCSResourceAttributes &attr,
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
BundleResource::setAttributes(attr);
}
virtual RCSResourceAttributes handleGetAttributesRequest(const
std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
return BundleResource::getAttributes();
}
};
virtual void handleSetAttributesRequest(const RCSResourceAttributes &attr,
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
BundleResource::setAttributes(attr);
}
virtual RCSResourceAttributes handleGetAttributesRequest(const
std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
return BundleResource::getAttributes();
}
};
virtual void handleSetAttributesRequest(const RCSResourceAttributes &attr,
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
BundleResource::setAttributes(attr);
}
virtual RCSResourceAttributes handleGetAttributesRequest(const
std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
return BundleResource::getAttributes();
}
except KeyError:
print ''
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
container_gtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
if target_os != 'android':
container_gtest_env.AppendUnique(CXXFLAGS = ['-pthread'])
test_bundle_env = container_gtest_env.Clone()
test_bundle_env.AppendUnique(CCFLAGS = ['-fPIC'])
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
test_bundle_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
TEST_BUNDLE_DIR = 'TestBundle/'
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')
RCSResourceAttributes handleGetAttributesRequest(
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
return BundleResource::getAttributes();
}
const RCSResourceAttributes &value,
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
BundleResource::setAttributes(value);
}
};
##
Import('env')
+rd_env = env.Clone()
-if env.get('RELEASE'):
- env.AppendUnique(CCFLAGS = ['-Os'])
- env.AppendUnique(CPPDEFINES = ['NDEBUG'])
-else:
- env.AppendUnique(CCFLAGS = ['-g'])
-
-if env.get('LOGGING'):
- env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
-
-lib_env = env.Clone()
-SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
-rd_env = lib_env.Clone()
+if rd_env.get('LOGGING'):
+ rd_env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
target_os = env.get('TARGET_OS')
+src_dir = env.get('SRC_DIR')
+
######################################################################
# Build flags
######################################################################
rd_env.AppendUnique(CPPPATH = ['include'])
rd_env.AppendUnique(CPPPATH = ['src/internal'])
-rd_env.AppendUnique(CPPPATH = ['../../resource/csdk/logger/include'])
-rd_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'libcoap'])
+rd_env.AppendUnique(CPPPATH = ['../../resource/csdk/stack/include'])
+rd_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap'])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
rd_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra'])
if target_os == 'linux':
######################################################################
RD_SRC_DIR = 'src/'
rd_src = [
- RD_SRC_DIR + '/internal/rd_storage.c',
+ RD_SRC_DIR + 'internal/rd_storage.c',
RD_SRC_DIR + 'rd_server.c',
RD_SRC_DIR + 'rd_client.c',
]
else :
rdsdk = rd_env.StaticLibrary('resource_directory', rd_src)
-rd_env.InstallTarget(rdsdk, 'libresource_directory')
-rd_env.UserInstallTargetLib(rdsdk, 'libresource_directory')
-rd_env.UserInstallTargetHeader('/include/rd_client.h', 'service/resource-directory', 'rd_client.h')
-rd_env.UserInstallTargetHeader('/include/rd_server.h', 'service/resource-directory', 'rd_server.h')
+rd_env.InstallTarget(rdsdk, 'resource_directory')
+rd_env.UserInstallTargetLib(rdsdk, 'resource_directory')
+rd_env.UserInstallTargetHeader('include/rd_client.h', 'service/resource-directory', 'rd_client.h')
+rd_env.UserInstallTargetHeader('include/rd_server.h', 'service/resource-directory', 'rd_server.h')
######################################################################
# Samples for the resource directory
######################################################################
-SConscript('samples/SConscript')
+if target_os not in ['windows']:
+ SConscript('samples/SConscript')
rd_sample_app_env = lib_env.Clone()
+target_os = env.get('TARGET_OS')
######################################################################
# Build flags
######################################################################
rd_sample_app_env.AppendUnique(CPPPATH = ['../include'])
-rd_sample_app_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra', '-std=c++0x'])
+if target_os not in ['windows']:
+ rd_sample_app_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra', '-std=c++0x'])
rd_sample_app_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
rd_sample_app_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
rd_sample_app_env.PrependUnique(LIBS = ['resource_directory', 'oc', 'octbstack'])
#include "rd_server.h"
#include <signal.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
int g_quitFlag = 0;
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "rd_storage.h"
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <string.h>
#include "payload_logging.h"
#define TAG PCF("RDStorage")
-pthread_mutex_t storageMutex = PTHREAD_MUTEX_INITIALIZER;
-// This variable holds the published resources on the RD.
+// Mutex implementation macros
+#if defined(HAVE_PTHREAD_H)
+
+#include <pthread.h>
+pthread_mutex_t storageMutex;
+#define MUTEX_LOCK(ARG_NAME) { pthread_mutex_lock(ARG_NAME); }
+#define MUTEX_UNLOCK(ARG_NAME) { pthread_mutex_unlock(ARG_NAME); }
+
+#elif defined(HAVE_WINDOWS_H)
+
+#include <windows.h>
+CRITICAL_SECTION storageMutex;
+#define MUTEX_LOCK(ARG_NAME) { EnterCriticalSection(ARG_NAME); }
+#define MUTEX_UNLOCK(ARG_NAME) { LeaveCriticalSection(ARG_NAME); }
+
+#else
+
+ERROR Need mutex implementation for this platform
+#define MUTEX_LOCK(ARG_NAME) { }
+#define MUTEX_UNLOCK(ARG_NAME) { }
+
+#endif
+
+
static OCRDStorePublishResources *g_rdStorage = NULL;
static void printStoragedResources(OCRDStorePublishResources *payload)
resources->publishedResource = storeResource;
resources->devAddr = *address;
- pthread_mutex_lock(&storageMutex);
+ MUTEX_LOCK(&storageMutex);
if (g_rdStorage)
{
OCRDStorePublishResources *temp = g_rdStorage;
{
g_rdStorage = resources;
}
- pthread_mutex_unlock(&storageMutex);
+ MUTEX_UNLOCK(&storageMutex);
printStoragedResources(g_rdStorage);
return OC_STACK_OK;
#include "oic_string.h"
#include "oic_malloc.h"
#include "payload_logging.h"
+#include "platform_features.h"
#include "rdpayload.h"
#include "ocpayload.h"
return result;
}
-static OCStackApplicationResult handlePublishCB(__attribute__((unused))void *ctx,
- __attribute__((unused)) OCDoHandle handle,
- __attribute__((unused)) OCClientResponse *clientResponse)
+static OCStackApplicationResult handlePublishCB(OC_ANNOTATE_UNUSED void *ctx,
+ OC_ANNOTATE_UNUSED OCDoHandle handle,
+ OC_ANNOTATE_UNUSED OCClientResponse *clientResponse)
{
OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;
OIC_LOG(DEBUG, TAG, "Successfully published resources.");
}
static OCStackApplicationResult handleDiscoverCB(void *ctx,
- __attribute__((unused)) OCDoHandle handle, OCClientResponse *clientResponse)
+ OC_ANNOTATE_UNUSED OCDoHandle handle, OCClientResponse *clientResponse)
{
OIC_LOG(DEBUG, TAG, "Found Resource Directory");
OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;
* will handle REST request (GET/PUT/POST/DEL) for them.
*/
static OCEntityHandlerResult rdEntityHandler(OCEntityHandlerFlag flag,
- OCEntityHandlerRequest *ehRequest, __attribute__((unused)) void *callbackParameter)
+ OCEntityHandlerRequest *ehRequest, OC_ANNOTATE_UNUSED void *callbackParameter)
{
OCEntityHandlerResult ehRet = OC_EH_ERROR;
resourceClient_env.PrependUnique(LIBS = ['oc', 'rcs_common', 'octbstack','oc_logger'])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
resourceClient_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
if target_os == 'linux':
resourceClient_env.AppendUnique(LIBS = ['pthread'])
ResourceClientsdk_static = resourceClient_env.StaticLibrary('rcs_client', client_src)
ResourceClientsdk_shared = resourceClient_env.SharedLibrary('rcs_client', client_src)
-resourceClient_env.InstallTarget([ResourceClientsdk_static,ResourceClientsdk_shared], 'librcs_client')
-resourceClient_env.UserInstallTargetLib([ResourceClientsdk_static,ResourceClientsdk_shared], 'librcs_client')
+resourceClient_env.InstallTarget([ResourceClientsdk_static,ResourceClientsdk_shared], 'rcs_client')
+resourceClient_env.UserInstallTargetLib([ResourceClientsdk_static,ResourceClientsdk_shared], 'rcs_client')
resourceClient_env.UserInstallTargetHeader('include/RCSAddress.h', 'service/resource-encapsulation', 'RCSAddress.h')
resourceClient_env.UserInstallTargetHeader('include/RCSDiscoveryManager.h', 'service/resource-encapsulation', 'RCSDiscoveryManager.h')
resourceClient_env.UserInstallTargetHeader('include/RCSRemoteResourceObject.h', 'service/resource-encapsulation', 'RCSRemoteResourceObject.h')
SConscript('src/resourceBroker/unittest/SConscript')
if target_os == 'android':
- SConscript('android/SConscript')
\ No newline at end of file
+ SConscript('android/SConscript')
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
},\r
{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/ad",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.ad"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } ,\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
"deviceuuid": "32323232-3232-3232-3232-323232323232",\r
"devowneruuid": "32323232-3232-3232-3232-323232323232",\r
"rowneruuid": "32323232-3232-3232-3232-323232323232",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
},\r
"cred": {\r
"creds": [\r
{\r
"href": "/oic/res",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.res"],\r
+ "if": ["oic.if.ll"]\r
},\r
{\r
"href": "/oic/d",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.d"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/p",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- },\r
- {\r
- "href": "/oic/res/types/d",\r
- "rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.p"],\r
+ "if": ["oic.if.baseline", "oic.if.r"]\r
},\r
{\r
"href": "/oic/ad",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.wk.ad"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/oic/sec/acl",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.acl"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/oic/sec/doxm",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
- } ,\r
+ "rt": ["oic.r.doxm"],\r
+ "if": ["oic.if.baseline"]\r
+ },\r
{\r
"href": "/oic/sec/pstat",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.r.pstat"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 2\r
{\r
"href": "/a/light",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.core"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/a/light0",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.core"],\r
+ "if": ["oic.if.baseline"]\r
},\r
{\r
"href": "/a/light1",\r
"rel": "",\r
- "rt": "",\r
- "if": ""\r
+ "rt": ["oic.core"],\r
+ "if": ["oic.if.baseline"]\r
}\r
],\r
"permission": 6\r
"deviceuuid": "31313131-3131-3131-3131-313131313131",\r
"devowneruuid": "32323232-3232-3232-3232-323232323232",\r
"rowneruuid": "31313131-3131-3131-3131-313131313131",\r
- "dpc": false\r
+ "x.com.samsung.dpc": false\r
},\r
"cred": {\r
"creds": [\r
#include <octypes.h>
+#include "boost/config.hpp"
+
namespace OIC
{
namespace Service
*/
explicit RCSException(std::string &&what);
- virtual ~RCSException() noexcept;
+ virtual ~RCSException() BOOST_NOEXCEPT;
/**
* Returns the exception description.
*
*/
- virtual const char *what() const noexcept;
+ virtual const char *what() const BOOST_NOEXCEPT;
private:
/**
class KeyValueVisitorHelper: public boost::static_visitor< >
{
public:
- KeyValueVisitorHelper(VISITOR& visitor) noexcept :
+ KeyValueVisitorHelper(VISITOR& visitor) BOOST_NOEXCEPT :
m_visitor( visitor )
{
}
*
* @see getBaseTypeId
*/
- TypeId getId() const noexcept;
+ TypeId getId() const BOOST_NOEXCEPT;
/**
* Returns the type identifier of a base type of sequence.
* @see getDepth
* @see getId
*/
- static TypeId getBaseTypeId(const Type& t) noexcept;
+ static TypeId getBaseTypeId(const Type& t) BOOST_NOEXCEPT;
/**
* Returns the depth of a type.
*
* @see getBaseTypeId
*/
- static size_t getDepth(const Type& t) noexcept;
+ static size_t getDepth(const Type& t) BOOST_NOEXCEPT;
/**
* Factory method to create Type instance from T.
* @see is_supported_type
*/
template < typename T >
- constexpr static Type typeOf(const T&) noexcept
+ constexpr static Type typeOf(const T&) BOOST_NOEXCEPT
{
return Type{ IndexOfType< T >::value };
}
* @see is_supported_type
*/
template < typename T >
- constexpr static Type typeOf() noexcept
+ constexpr static Type typeOf() BOOST_NOEXCEPT
{
return Type{ IndexOfType< T >::value };
}
//! @cond
- friend bool operator==(const Type&, const Type&) noexcept;
+ friend bool operator==(const Type&, const Type&) BOOST_NOEXCEPT;
//! @endcond
private:
- constexpr explicit Type(int which) noexcept :
+ constexpr explicit Type(int which) BOOST_NOEXCEPT :
m_which{ which }
{
}
Value();
Value(const Value&);
- Value(Value&&) noexcept;
+ Value(Value&&) BOOST_NOEXCEPT;
/**
* Constructs a Value if T is a supported type.<br/>
/**
* Exchanges the content of the object by the content of the parameter.
*/
- void swap(Value&) noexcept;
+ void swap(Value&) BOOST_NOEXCEPT;
//! @cond
friend class RCSResourceAttributes;
/**
* Returns an {@link iterator} referring to the first element.
*/
- iterator begin() noexcept;
+ iterator begin() BOOST_NOEXCEPT;
/**
* Returns an {@link iterator} referring to the <i>past-the-end element</i>.
*/
- iterator end() noexcept;
+ iterator end() BOOST_NOEXCEPT;
/**
* @copydoc cbegin()
*/
- const_iterator begin() const noexcept;
+ const_iterator begin() const BOOST_NOEXCEPT;
/**
* @copydoc cend()
*/
- const_iterator end() const noexcept;
+ const_iterator end() const BOOST_NOEXCEPT;
/**
* Returns a const_iterator referring to the first element.
*/
- const_iterator cbegin() const noexcept;
+ const_iterator cbegin() const BOOST_NOEXCEPT;
/**
* Returns a const_iterator referring to the <i>past-the-end element</i>.
*/
- const_iterator cend() const noexcept;
+ const_iterator cend() const BOOST_NOEXCEPT;
/**
* Accesses a value.
/**
* Removes all elements.
*/
- void clear() noexcept;
+ void clear() BOOST_NOEXCEPT;
/**
* Removes a single element.
*
* @see size
*/
- bool empty() const noexcept;
+ bool empty() const BOOST_NOEXCEPT;
/**
* Returns the number of elements.
*
* @see empty
*/
- size_t size() const noexcept;
+ size_t size() const BOOST_NOEXCEPT;
private:
template< typename VISITOR >
* @return true if the objects are equal, false otherwise.
*/
bool operator==(const RCSResourceAttributes::Type&, const RCSResourceAttributes::Type&)
- noexcept;
+ BOOST_NOEXCEPT;
/**
* @relates RCSResourceAttributes::Type
* @return true if the objects are not equal, false otherwise.
*/
bool operator!=(const RCSResourceAttributes::Type&, const RCSResourceAttributes::Type&)
- noexcept;
+ BOOST_NOEXCEPT;
/**
* @relates RCSResourceAttributes::Value
class KeyVisitor: public boost::static_visitor< const std::string& >
{
public:
- result_type operator()(iterator*) const noexcept;
- result_type operator()(const_iterator*) const noexcept;
+ result_type operator()(iterator*) const BOOST_NOEXCEPT;
+ result_type operator()(const_iterator*) const BOOST_NOEXCEPT;
};
class ValueVisitor: public boost::static_visitor< Value& >
{
public:
- result_type operator()(iterator*) noexcept;
+ result_type operator()(iterator*) BOOST_NOEXCEPT;
result_type operator()(const_iterator*);
};
class ConstValueVisitor: public boost::static_visitor< const Value& >
{
public:
- result_type operator()(iterator*) const noexcept;
- result_type operator()(const_iterator*) const noexcept;
+ result_type operator()(iterator*) const BOOST_NOEXCEPT;
+ result_type operator()(const_iterator*) const BOOST_NOEXCEPT;
};
public:
- const std::string& key() const noexcept;
- const RCSResourceAttributes::Value& value() const noexcept;
+ const std::string& key() const BOOST_NOEXCEPT;
+ const RCSResourceAttributes::Value& value() const BOOST_NOEXCEPT;
RCSResourceAttributes::Value& value();
private:
KeyValuePair(const KeyValuePair&) = default;
- KeyValuePair(boost::variant< iterator*, const_iterator* >&&) noexcept;
+ KeyValuePair(boost::variant< iterator*, const_iterator* >&&) BOOST_NOEXCEPT;
KeyValuePair& operator=(const KeyValuePair&) = default;
* in instead of overriding SetRequestHandler.
* </p>
*/
+
class RCSResourceObject
{
private:
- class WeakGuard;
typedef AtomicWrapper< std::thread::id > AtomicThreadId;
+ //! @cond
+ class WeakGuard
+ {
+ public:
+ WeakGuard(const RCSResourceObject&);
+ ~WeakGuard();
+
+ WeakGuard(const WeakGuard&) = delete;
+ WeakGuard(WeakGuard&&) = delete;
+
+ WeakGuard& operator=(const WeakGuard&) = delete;
+ WeakGuard& operator=(WeakGuard&&) = delete;
+
+ bool hasLocked() const;
+
+ private:
+ bool m_isOwningLock;
+ const RCSResourceObject& m_resourceObject;
+ };
+ //! @endcond
+
public:
+
/**
* Represents the policy of auto-notify function.
* In accord with this policy, observers are notified of attributes
template< typename T >
T getAttribute(const std::string& key) const
{
- WeakGuard lock(*this);
+ RCSResourceObject::WeakGuard lock(*this);
return m_resourceAttributes.at(key).get< T >();
}
std::function<void()> m_autoNotifyFunc;
};
- //! @cond
- class RCSResourceObject::WeakGuard
- {
- public:
- WeakGuard(const RCSResourceObject&);
- ~WeakGuard();
-
- WeakGuard(const WeakGuard&) = delete;
- WeakGuard(WeakGuard&&) = delete;
-
- WeakGuard& operator=(const WeakGuard&) = delete;
- WeakGuard& operator=(WeakGuard&&) = delete;
-
- bool hasLocked() const;
-
- private:
- bool m_isOwningLock;
- const RCSResourceObject& m_resourceObject;
- };
- //! @endcond
}
}
rcs_common_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
rcs_common_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
if target_os != 'android':
rcs_common_env.AppendUnique(CXXFLAGS = ['-pthread'])
rcs_common_env.AppendUnique(LIBS = ['pthread'])
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
rcs_common_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
if target_os == 'android':
broker_test_env.AppendUnique(LIBS = [gtest])
broker_test_env.AppendUnique(LIBS = [gtest_main])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
broker_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
if target_os == 'linux':
cache_test_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
cache_test_env.PrependUnique(LIBS = ['rcs_client', 'rcs_common', 'oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', gtest, gtest_main])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
cache_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
if target_os == 'linux':
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')
server_builder_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
server_builder_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
if target_os != 'android':
server_builder_env.AppendUnique(CXXFLAGS = ['-pthread'])
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
server_builder_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
if target_os == 'android':
m_resourceObject, m_resourceObject.m_resourceAttributes, m_autoNotifyPolicy);
}
- RCSResourceObject::WeakGuard::WeakGuard(
+ RCSResourceObject::WeakGuard::WeakGuard(
const RCSResourceObject& resourceObject) :
m_isOwningLock{ false },
m_resourceObject(resourceObject)
'../src/common/utils/include',
])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
rcs_test_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
if target_os != 'android':
rcs_test_env.AppendUnique(CXXFLAGS = ['-pthread'])
'libcoap'
])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
resourcehosting_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
resourcehosting_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
if target_os == 'linux':
else :
resourcehostingsdk = resourcehosting_env.StaticLibrary('resource_hosting', resourcehosting_src)
-resourcehosting_env.InstallTarget(resourcehostingsdk, 'libresource_hosting')
-resourcehosting_env.UserInstallTargetLib(resourcehostingsdk, 'libresource_hosting')
+resourcehosting_env.InstallTarget(resourcehostingsdk, 'resource_hosting')
+resourcehosting_env.UserInstallTargetLib(resourcehostingsdk, 'resource_hosting')
resourcehosting_env.UserInstallTargetHeader('include/Hosting.h',\
'service/resource-hosting', 'Hosting.h')
#include "RCSRemoteResourceObject.h"
#include "RCSResourceObject.h"
+#ifdef _MSC_VER
+#define OIC_HOSTING_LOG(level, fmt, ...) OIC_LOG_V((level), PCF("Hosting"), fmt, __VA_ARGS__)
+#else
#define OIC_HOSTING_LOG(level, fmt, args...) OIC_LOG_V((level), PCF("Hosting"), fmt, ##args)
+#endif
namespace OIC
{
'oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap',
GTest_Main, GTest])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
hosting_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
if target_os == 'linux':
target_os = env.get('TARGET_OS')
if target_os == 'linux':
from tools.scons.RunTest import *
- run_test(hosting_test_env, '', 'service/resource-hosting/unittest/hosting_test')
\ No newline at end of file
+ run_test(hosting_test_env, '', 'service/resource-hosting/unittest/hosting_test')
'rcs_common'
])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
scenemanager_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
scenemanager_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
if target_os == 'linux':
'oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap',
GTest_Main, GTest])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
scene_test_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
if target_os == 'linux':
# 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')
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;
things_manager_env.PrependUnique(LIBS = ['oc', 'octbstack'])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
things_manager_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
if target_os != 'android':
things_manager_env.AppendUnique(CXXFLAGS = ['-pthread'])
things_manager_env.AppendUnique(LIBS = ['pthread'])
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
things_manager_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
if target_os == 'android':
#include <vector>
#include <cstdio>
#include <iostream>
-
#include <ctime>
-
#include <timer.h>
using namespace std;
tm_jni_env.AppendUnique(CPPPATH = [base_jni])
tm_jni_env.AppendUnique(CPPPATH = ['tm/inc', 'jniutil/inc', extlibs+'/timer/'])
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows']:
tm_jni_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
######################################################################
#include <algorithm>
#include <thread>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
#include <string.h>
#include "GroupManager.h"
'../../../extlibs/timer'
])
-if target_os not in ['windows', 'winrt']:
+if target_os not in ['windows']:
ThingsManager_gtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
if target_os != 'android':
ThingsManager_gtest_env.AppendUnique(CXXFLAGS = ['-pthread'])
elif target_os == 'darwin':
lib_env.AppendUnique(CPPPATH = ['/usr/local/include'])
lib_env.AppendUnique(LIBPATH = ['/usr/local/lib'])
+elif target_os == 'windows':
+ boost_path = os.path.join(src_dir,'extlibs','boost','boost')
+ lib_env.AppendUnique(CPPPATH = [boost_path])
Import('env')
lib_env.AppendUnique(LIBPATH = env.get('BUILD_DIR'))
cp -r resource/csdk/stack/include/*.h $FRAMEWORK_BUNDLE/Headers
cp -r resource/csdk/ocsocket/include/*.h $FRAMEWORK_BUNDLE/Headers
cp -r resource/c_common/ocrandom/include/*.h $FRAMEWORK_BUNDLE/Headers
-cp -r resource/csdk/ocmalloc/include/*.h $FRAMEWORK_BUNDLE/Headers
+cp -r resource/c_common/oic_malloc/include/*.h $FRAMEWORK_BUNDLE/Headers
echo "Framework: Creating plist..."
cat > $FRAMEWORK_BUNDLE/Resources/Info.plist <<EOF
echo "Framework: Copying includes..."
cp -r resource/csdk/stack/include/*.h $FRAMEWORK_BUNDLE/Headers
cp -r resource/c_common/ocrandom/include/*.h $FRAMEWORK_BUNDLE/Headers
-cp -r resource/csdk/ocmalloc/include/*.h $FRAMEWORK_BUNDLE/Headers
+cp -r resource/c_common/oic_malloc/include/*.h $FRAMEWORK_BUNDLE/Headers
echo "Framework: Creating plist..."
cat > $FRAMEWORK_BUNDLE/Resources/Info.plist <<EOF
test_cmd = os.path.join(build_dir, test)
- if xml_file:
+ have_valgrind = False
+ if env.get('TARGET_OS') not in ['windows']:
+ have_valgrind = True
+
+ if xml_file and have_valgrind:
# Environment variables to be made available during the
# Valgrind run.
valgrind_environment = ''
# read the tools on *nix systems and sets the default parameters
- elif env["PLATFORM"] in ["darwin", "linux", "posix"] :
+ elif env["PLATFORM"] in ["darwin", "linux", "posix", "msys"] :
if env.WhereIs("unzip") :
toolset["EXTRACTOR"]["ZIP"]["RUN"] = "unzip"
Name: iotivity
-Version: 1.1.0
+Version: 1.1.1
Release: 0
Summary: IoT Connectivity sponsored by the OIC
Group: Network & Connectivity/Other